c++ - 字面量类型在运行时的惊人行为

标签 c++ clang c++14

我对这段用 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/

相关文章:

c++ - 移出三元运算符的一侧

c++ - 如何在运行时从表示函数的字符串执行 C++ 代码?

c++ - POD 类型的二进制 I/O 如何不破坏别名规则?

c++ - 如何在连续内存中多态地存储和访问来自同一继承层次结构的不同类型?

c++ - 无法在未指定捕获默认值的 lambda 中隐式捕获变量

c++ - 在 C++ 中创建结构数组

c++ - std::ifstream::operator>> 无法将 0xABCD 转换为短字符?

c++ - 在发布版本中使用 assert() 时避免未使用的变量警告

android - android中的g++和ubuntu中的g++有什么区别?

c++ - LLVMContext 作为类成员会破坏构造函数吗?