User-declared default constructor + in-class initializers != user-provided constructor? [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-05 13:01:34

问题


The Clang documentation neatly explains that

If a class or struct has no user-defined default constructor, C++ doesn't allow you to default construct a const instance of it like this ([dcl.init], p9)

The rationale being that if a const object is not correctly initialized, it cannot be changed later on. The following code has only a user-declared default constructor for Test, but all its members have in-class initializers,

#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
}

so the rationale for also user-providing the default constructor seems superfluous to me. And indeed, g++ 4.8.1 does compile it without problems (Online Example), although Clang <= 3.2 does not.

Questions: why is the combination of complete in-class initalizers + user-declared default constructor not enough to default construct a const object? Is there a fix underway for the C++14 Standard?

UPDATE: can anyone try on Clang 3.3 / 3.4 to see if this has been fixed compared to Clang 3.2?


回答1:


Yes, this is a known problem. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#253 . It hasn't been fixed yet in the spec.



来源:https://stackoverflow.com/questions/17497555/user-declared-default-constructor-in-class-initializers-user-provided-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!