value initialization for automatic variables [duplicate]

孤者浪人 提交于 2020-01-25 00:08:25

问题


Possible Duplicate:
non-copyable objects and value initialization: g++ vs msvc
Value-initializing an automatic object?

Consider the following statement:

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();
}

回答1:


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();

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
}

SINCE C++11: int i{}; does the job (see also this).



来源:https://stackoverflow.com/questions/9346687/value-initialization-for-automatic-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!