用户声明的默认构造函数+类内初始化程序!=用户提供的构造函数? [英] User-declared default constructor + in-class initializers != user-provided constructor?

查看:87
本文介绍了用户声明的默认构造函数+类内初始化程序!=用户提供的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clang文档清楚地说明了


如果类或结构没有用户定义的默认构造函数,C ++
不允许您默认构造其const实例,例如
this([dcl.init] ,p9)

If a class or struct has no user-defined default constructor, C++ doesn't allow you to default construct a const instance of it like this ([dcl.init], p9)

基本原理是,如果未正确初始化const对象,则以后无法更改它。以下代码仅具有用于 Test 的用户声明的默认构造函数,但其​​所有成员均具有类内初始化程序

The rationale being that if a const object is not correctly initialized, it cannot be changed later on. The following code has only a user-declared default constructor for Test, but all its members have in-class initializers,

#include<iostream>

class Test
{
public:
    Test() = default;
    void print() const { std::cout << i << "\n"; }
private:
    int i = 42;   // will propagate to the default constructor!
};

int main()
{
    Test const t; // <-- Clang chokes on the const keyword, g++ does not
    t.print();    // prints 42
}

因此用户-提供默认构造函数对我来说是多余的。确实,g ++ 4.8.1确实可以毫无问题地进行编译(在线示例),尽管 Clang< = 3.2 不会。

so the rationale for also user-providing the default constructor seems superfluous to me. And indeed, g++ 4.8.1 does compile it without problems (Online Example), although Clang <= 3.2 does not.

问题:为什么完整的课堂诱因+用户-声明默认构造函数不足以默认构造const对象吗? C ++ 14标准是否正在修复?

Questions: why is the combination of complete in-class initalizers + user-declared default constructor not enough to default construct a const object? Is there a fix underway for the C++14 Standard?

更新:是否有人可以尝试使用Clang 3.3 / 3.4来查看与Clang 3.2相比是否已解决?

UPDATE: can anyone try on Clang 3.3 / 3.4 to see if this has been fixed compared to Clang 3.2?

推荐答案

是的,这是一个已知问题。参见 http://www.open-std.org/jtc1/sc22/wg21 /docs/cwg_active.html#253 。规格尚未修复。

Yes, this is a known problem. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#253 . It hasn't been fixed yet in the spec.

这篇关于用户声明的默认构造函数+类内初始化程序!=用户提供的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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