User-declared default constructor + in-class initi

2020-07-02 12:29发布

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条回答
祖国的老花朵
2楼-- · 2020-07-02 13:18

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.

查看更多
登录 后发表回答