Clang Compile error with default initialization [duplicate]

一个人想着一个人 提交于 2019-11-28 08:37:54

问题


Consider following example:

#include <iostream>
#include <type_traits>

struct A
{
  //A() = default; // does neither compile with, nor without this line
  //A(){};         // does compile with this line
  int someVal{ 123 };


  void foobar( int )
  {
  };
};


int main()
{
    const A a;
    std::cout << "isPOD = " << std::is_pod<A>::value << std::endl;
    std::cout << "a.someVal = " <<a.someVal << std::endl;
}

See Live example

This does compile with g++ but does not compile with clang++, tried with following command: clang++ -std=c++11 -O0 main.cpp && ./a.out

Compile error from clang:

main.cpp:19:13: error: default initialization of an object of const type 'const A' requires a user-provided default constructor

I learned from This Stack Overflow Question, that non-POD classes get default constructor. This is even not necessary here because the variable has c++11-style default initialization

Why does this not for clang? Why does A() = default; not work, too?


回答1:


You quoted the answer yourself. In the SO answer that you linked, there is the following quote from the standard (section 6.8.6precisely):

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

emphasis mine. The line

A() = default;

obviously does not provide a constructor, it does the opposite by telling the compiler that you don't want to provide one, thus your code doesn't compile. However, once you provide the constructor by uncommenting

 A(){}; 

it works fine. So, to summarize, the error that clang shows is per standard, and the behaviour of gcc is probably a bug.




回答2:


This is addressed in CWG issue #253 which discusses the need for a user provided constructor for empty objects or objects whose subobjects are fully initialized (which is the case in your example).

Quoting part of the linked issue

Notes from the August, 2011 meeting:

If the implicit default constructor initializes all subobjects, no initializer should be required.

Technically it is an active issue but given that note it seems likely that it'll be resolved the way gcc chose to implement it.

Clang, on the other hand, has chosen to wait until the issue is resolved before implementing a solution.

In Clang, we're waiting for the issue to actually be resolved before we take a direction on it.

So, as it currently stands, clang is correct.



来源:https://stackoverflow.com/questions/28337951/clang-compile-error-with-default-initialization

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