加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – Clang编译错误,默认初始化

发布时间:2020-12-16 09:56:17 所属栏目:百科 来源:网络整理
导读:参见英文答案 Do I really need to implement user-provided constructor for const objects?????????????????????????????????????3个 考虑以下示例: #include iostream#include type_traitsstruct A{ //A() = default; // does neither compile with,nor
参见英文答案 > Do I really need to implement user-provided constructor for const objects?????????????????????????????????????3个
考虑以下示例:

#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

这用g编译,但不用clang编译,尝试使用以下命令:clang -std = c 11 -O0 main.cpp&& ./a.out

从clang编译错误:

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

我从This Stack Overflow Question学到了非POD类获得默认构造函数.这甚至不是必需的,因为变量具有c 11样式的默认初始化

为什么这不是为了铿锵?
为什么A()=默认值;也不行吗?

解决方法

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

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;

显然不提供构造函数,它通过告诉编译器你不想提供一个构造函数来反过来,因此你的代码不会编译.但是,一旦通过取消注释提供构造函数

A(){};

它工作正常.因此,总而言之,clang显示的错误是按标准进行的,而gcc的行为可能是一个错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读