c++ - c++11 get string length in compile time by constexpr -
#include <stdio.h> constexpr size_t constlength(const char* str) { return (*str == 0) ? 0 : constlength(str + 1) + 1; } int _tmain(int argc, _tchar* argv[]) { const char* p = "1234567"; size_t = constlength(p); printf(p); printf("%d", i); return 0; }
hi,all want length of string in compile-time.so wrote code above.but in disassembly code found 'constlength' function named sub_401000 below lead run-time overhead computting length of string.is there wrong?(visual studio 2015 preview,release maximize speed (/o2) optimization)
int __cdecl sub_401010() { int v0; // esi@1 v0 = sub_401000("234567") + 1; sub_401040(&unk_402130); sub_401040("%d"); return 0; } int __thiscall sub_401000(void *this) { int result; // eax@2 if ( *(_byte *)this ) result = sub_401000((char *)this + 1) + 1; else result = 0; return result; }
a constexpr
function can evaluated @ compile time when called arguments compile-time constants. although value of p
can determined static analysis (it doesn't change between initialization , evaluation), it's not constant expression per standard definition.
try this:
constexpr const char* p = "1234567";
also, can guarantee initialization doable without runtime overhead declaring initialized variable constexpr
:
constexpr size_t = constlength(p);
Comments
Post a Comment