我真的需要实现用户提供的构造函数的const对象吗

我真的需要实现用户提供的构造函数的const对象吗

本文介绍了我真的需要实现用户提供的构造函数的const对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有代码:class A { public: A() = default; private: int i = 1;};int main() { const A a; return 0;}它在g ++上编译良好(参见ideone ),但在clang ++上失败,并显示错误:It compiles fine on g++ (see ideone), but fails on clang++ with error:我在 LLVM bug-tracker 并获得了INVALID。I reported this issue on LLVM bug-tracker and got it INVALID.我看到它绝对无意义试图说服ang开发商。另一方面,我没有看到这种限制的原因。I see it absolutly pointless to try to convince the clang developers. On the other side, I don't see the reason for such restriction.任何人都可以建议,如果C + +11标准不知何故暗示这个代码无效?或者我应该向g ++报告一个错误?Can anyone advise, if the C++11 Standard somehow implies this code to be invalid? Or should I just report a bug to g++? Or maybe there is enough freedom in language rules to handle this code in many ways?推荐答案 N3797§8.5/ 7说:N3797 §8.5/7 says:没有更多的示例或解释。我同意这似乎很奇怪。此外,当类类型需要用户声明的构造函数时,在C ++ 11中更新的规则比在C ++ 03中更加限制。 (您的构造函数是用户声明的。)There's no further example or explanation of this. I agree it seems pretty bizarre. Furthermore the rule was updated in C++11 to be more restrictive than it was in C++03, when class types needed user-declared constructors. (Your constructor is user-declared.)解决方法是使用 {} 或者使用Dietmar的聪明的 inline 定义。The workaround is be to ask for value initialization using {}, or use Dietmar's clever out-of-class inline definition. GCC确实提供了诊断GCC does provide a diagnosis (and quite a nice one, referring to the newer C++11 requirements) if you add another member without an initializer. 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; GCC 来源指代 DR 253 ,为什么必须初始化空或全初始化的const对象?标准中的一个开放性问题,最后更新于2011年8月(后C ++ 11)与此注释:The GCC source refers to DR 253, Why must empty or fully-initialized const objects be initialized? This is an open issue in the standard, last updated in August 2011 (post-C++11) with this note:因此,Clang符合C ++ 11与C ++ 14),GCC正在实施标准化委员会的最新思想。Therefore whereas Clang complies with C++11 (and will comply as-is with C++14), GCC is implementing the latest thinking of the standardization committee.提交了 GCC错误。我预测,当(和如果)修复错误时,您需要 -pedantic 才能获得诊断。Filed a GCC bug. I predict that you'll need -pedantic to get a diagnosis when (and if) the bug is fixed. 这篇关于我真的需要实现用户提供的构造函数的const对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-18 13:30