c++ - 我真的需要为 const 对象实现用户提供的构造函数吗?

我有代码:

class A {
  public:
    A() = default;

  private:
    int i = 1;
};

int main() {
  const A a;
  return 0;
}

它在 g++ 上编译良好(参见 ideone ),但在 clang++ 上编译失败并出现错误:

default initialization of an object of const type 'const A' requires a user-provided default constructor

我在 LLVM bug-tracker 上报告了此问题并认为它无效。

我认为试图说服 clang 开发人员是毫无意义的。另一方面,我看不出这种限制的原因。


如果 C++11 标准以某种方式暗示此代码无效,任何人都可以提出建议吗?还是我应该只向 g++ 报告一个错误?或者也许语言规则有足够的自由度以多种方式处理此代码?

最佳答案

N3797 §8.5/7 说:

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.

没有更多的例子或解释。我同意这看起来很奇怪。此外,当类类型需要 user-declared 构造函数时,该规则在 C++11 中更新为比在 C++03 中更具限制性。 (您的构造函数是用户声明的。)

解决方法是使用 {} 请求值初始化,或者使用 Dietmar 的聪明的类外 inline 定义。

如果您在没有初始化程序的情况下添加另一个成员,GCC 确实提供了一个诊断(而且相当不错,指的是较新的 C++11 要求)。

  private:
    int i = 1;
    int j;

 

unmem.cpp:11:11: error: uninitialized const ‘a’ [-fpermissive]
   const A a;
           ^
unmem.cpp:1:7: note: ‘const class A’ has no user-provided default constructor
 class A {
       ^
unmem.cpp:3:5: note: constructor is not user-provided because it is explicitly defaulted in the class body
     A() = default;
     ^
unmem.cpp:7:9: note: and the implicitly-defined constructor does not initialize ‘int A::j’
     int j;

海合会 source指DR 253 , 为什么必须初始化空的或完全初始化的 const 对象? 这是标准中的一个未解决问题,最后更新于 2011 年 8 月(C++11 后),并附有以下说明:

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

因此,尽管 Clang 符合 C++11(并将按原样符合 C++14),但 GCC 正在实现标准化委员会的最新思想。

提交了 GCC bug .我预测您将需要 -pedantic 来在错误得到修复时(以及是否)得到诊断。

https://stackoverflow.com/questions/21900237/

相关文章:

c++ - 如何轻松查看 C/C++ #include 图?

c++ - 在函数模板中使用静态局部变量的地址作为类型标识符是否安全?

c++ - 将多个参数传递到 std::thread

c++ - C++ 异常处理如何转化为机器码

c++ - 特殊情况: Is & faster than %?

c++ - std::this_thread::yield() 与 std::this_thread

c++ - std::atomic 是否正常工作?

c++ - 我必须明确调用原子加载/存储吗?

c++ - 为什么 move 指针变量不会将其设置为空?

c++ - C++ 中是否存在比 long long int 更大的类型?