1

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();
}
Community
  • 1
  • 1
T.J.
  • 1,466
  • 3
  • 19
  • 35
  • 3
    Your `i` is copy-initialized, not value-initialized. Only the temporary is value-initialized. – Kerrek SB Feb 19 '12 at 04:32
  • possible duplicate of [Value-initializing an automatic object?](http://stackoverflow.com/questions/6298001/value-initializing-an-automatic-object) and http://stackoverflow.com/questions/2671532/non-copyable-objects-and-value-initialization-g-vs-msvc – Ben Voigt Feb 19 '12 at 04:52

1 Answers1

3

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

JtTest
  • 47
  • 9
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • :is int i(6) a value initialization and what will int i(int()) means – T.J. Feb 19 '12 at 05:28
  • why this is value initialization?? T * p2 = new T(); – T.J. Feb 19 '12 at 05:34
  • The form `int i(6)` is _direct-initialization_ (8.5 [dcl.init] paragraph 15). `int i(int())` declares a function named `i` returning an `int` and taking a function with no arguments and returning `int` as argument. In `T* p2 = new T()` the `new`ed object is value-initialized, the pointer `p2` is copy initialized. – Dietmar Kühl Feb 19 '12 at 08:31