Question

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();
}
Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top