Clang使用默认初始化编译错误 [英] Clang Compile error with default initialization

查看:169
本文介绍了Clang使用默认初始化编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

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

查看实例

这是用g ++编译的,但不能用clang ++编译, clang ++ -std = c ++ 11 -O0 main.cpp&&& ./a.out

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

从clang中编译错误:

Compile error from clang:


main.cpp:19:13:error:const类型为const A的对象的默认初始化需要用户提供的默认构造函数

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

我从这个堆栈溢出问题,非POD类获得默认构造函数。这在这里甚至不是必需的,因为变量具有c ++ 11样式的默认初始化

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

为什么不是clang?
为什么 A()= default; 不起作用。

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

推荐答案

你自己引用了答案。在链接的SO答案中,标准中有以下引用(6.8.6节精确地):

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



const限定类型T,T的对象的默认初始化应该是具有用户提供的
默认构造函数的类类型。

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.

强调我。

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(){}; 

它工作正常。所以,总结一下,clang显示的错误是每个标准,gcc的行为可能是一个错误。

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

这篇关于Clang使用默认初始化编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆