Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 321
TemplateRex Avatar asked Jul 05 '13 22:07

TemplateRex


1 Answers

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.

like image 135
Johannes Schaub - litb Avatar answered Oct 17 '22 23:10

Johannes Schaub - litb