且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动变量的值初始化

更新时间:2023-11-10 20:44:16

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
}