This question already has answers here:
Why does C++ require a user-provided default constructor to default-construct a const object?

(5个答案)


3年前关闭。




Clang documentation巧妙地说明了这一点



基本原理是,如果未正确初始化const对象,则以后无法更改它。以下代码只有一个用户声明为Test的缺省构造函数,但其所有成员都具有类内初始化程序,
#include<iostream>

class Test
{
public:
    Test() = default;
    void print() const { std::cout << i << "\n"; }
private:
    int i = 42;   // will propagate to the default constructor!
};

int main()
{
    Test const t; // <-- Clang chokes on the const keyword, g++ does not
    t.print();    // prints 42
}

因此,用户也为提供默认构造函数的理由在我看来是多余的。确实,尽管 Clang 没有,但g++ 4.8.1确实可以毫无问题地编译它(Online Example)。

问题:为什么完整的类初始化器+用户声明的默认构造函数的组合不足以默认构造const对象? C++ 14标准是否正在修复?

更新:有人可以尝试使用Clang 3.3/3.4来查看与Clang 3.2相比是否已修复?

最佳答案

是的,这是一个已知问题。参见http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#253。尚未在规范中修复它。

10-06 05:23
查看更多