我对这段用 clang 3.9 编译的代码的行为感到有点困惑:
struct A {
constexpr A() = default;
A(const A&) = delete;
constexpr A(A&&) {}
A& operator =(const A&) = delete;
constexpr A& operator =(A&&) { return *this; }
constexpr operator bool() const { return &self == this; }
private:
A& self{*this};
};
constexpr A fooA() { return {}; }
int main(int argc, const char * argv[]) {
static_assert(fooA(), "");
return fooA();
}
Godbolt 链接:https://godbolt.org/g/CDFXAc
fooA
的静态/编译时评估正确发生;但是在运行时,构造函数似乎被完全省略了。 static_assert
没有触发(如预期的那样)但 main 仍然返回 0。这是因为 A
是文字类型还是因为编译器错误?
如果是前者,我们将不胜感激任何对标准的引用。
最佳答案
这是一个更简化的例子:
struct A {
constexpr A() : self(this) { }
A* self;
};
int main() {
constexpr A a{};
}
gcc 和 clang 都不接受此代码,因为它们不喜欢在初始化程序中使用 this
。但是,this
允许出现在常量表达式中,只要它在 constexpr
构造函数中,因为 N3652 . MSVC 做对了。
关于c++ - 字面量类型在运行时的惊人行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566780/