次の例では、static_assert
を使用して、foo
がコンパイル時に決定されることを確認します。 static_assert
が合格し、私はそれが実際にアクティブである間違った条件でチェックしました。これは、コンパイル時にfoo
がわかっていることを意味します。しかし、デバッガでコードをステップ実行すると、実行時にskip_first_word
も実行されることがわかります。コンパイル時および実行時に評価されるconst char * constexpr
// Skip the first word in p_str
constexpr const char * skip_first_word(const char * p_str) {
return (*p_str == '\0') ? p_str :
(*p_str == ' ') ? p_str + 1 :
skip_first_word(p_str + 1);
}
// constexpr to calculate the length of a string
constexpr size_t str_len(const char * p_str) {
return (*p_str == '\0') ? 0 : str_len(p_str + 1) + 1;
}
int main()
{
constexpr auto foo = skip_first_word("Hello, World!");
constexpr auto foo_size = str_len(foo);
static_assert(foo_size == 6, "Wrong size");
// This assert successfully fails
// static_assert(foo_size == 7, "Wrong size");
// Prevent optimizations
for(auto ptr = foo; *ptr != '\0'; ++ptr) {
volatile auto sink = ptr;
}
volatile auto sink = &foo_size;
return 0;
}
ここでは何が起こっていますか?コンパイル時に計算されたfoo
を実行時に使用できないのはなぜですか?
編集:この動作は、Visual Studioの2015
両方のケースで同じ最適化レベルを使用しましたが、それは正しいですか? –
@ n.caillouはい、最適化の有無にかかわらず両方のケースを実行しました。 –
@FrançoisAndrieux:VS2015の動作をカバーするために私の答えを更新しました –