自动变量的值初始化 [英] value initialization for automatic variables

查看:137
本文介绍了自动变量的值初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

非可复制对象和值初始化:g ++ vs msvc

值初始化自动对象?

请考虑以下语句:


这不是真正可能的值初始化一个自动对象。

It's not really possible to value-initialize an automatic object.

这句话是真的吗?我看到没有问题这样做:

Is this statement true? I see no problem in doing this:

int main()
{
    int i = int();
}


推荐答案

c> value-initialization 定义在8.5 [dcl.init]段落16,第四个项目符号:

The term value-initialization is defined in 8.5 [dcl.init] paragraph 16, 4th bullet:


If the initializer is (), the object is value-initialized.

也就是说,自动变量的值初始化看起来像这样: :

That is, value-initialization of an automatic variable would look like this:

int i();

但是,这是一个函数的声明 i 返回 int 。因此,不可能对自动值进行值初始化。在您的示例中,临时值是值初始化的,自动变量是复制初始化的。您可以验证这确实需要使用没有可访问的复制构造函数的测试类访问复制构造函数:

However, this is a declaration of a function called i returning an int. Thus, it is impossible to value-initialize an automatic. In your example, the temporary is value-initialized and the automatic variable is copy-initialized. You can verify that this indeed requires the copy constructor to be accessible using a test class which doesn't have an accessible copy constructor:

class noncopyable {
    noncopyable(noncopyable const&);
public:
    noncopyable();
};

int main() {
    noncopyable i = noncopyable(); // ERROR: not copyable
}

这篇关于自动变量的值初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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