Why does initializer-list not value-initialize a struct? A bug of VC++?

X

xmllmx

The C++11 standard 8.5.4.3 says:

"If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized."

struct A
{
int get() { return i; }

private:
int i;
};

int main()
{
A a = {};

int n = a.get();
cout << n << endl;
// n is 0xCCCCCCCC rather than 0 when running in debugging mode.

return 0;
}

Is this a bug of VC++? My VC++ is the latest Nov 2012 CTP.
 
Z

Zhihao Yuan

Is this a bug of VC++? My VC++ is the latest Nov 2012 CTP.

Your example works with clang/gcc.

This may not be a bug. I never used VC++, but, can you try
to remove the private: line and compile your program without
C++11? Since VC++ may be trying to issue an warning for a
particular usage (value initialization, or a C style empty
init-list).
 
B

Balog Pal

I don't see a default constructor, as required by that paragraph.

I see nothing that would prevent creation of the defaulted default ctor,
so IMO the verdict applies to the situation.

But it's interesting experiment what happens if
A() = default;
is inserted. I'd expect no change.

OTOH I don't really get the standard's intent here. Suppose I have the
class like this:


struct A
{
A() : i(66) {}
int i, j;
};

then I'd expect A{} have i==66 rather than 0 due to value init. Or is
there a continuation that executes the ctor after value init, so I get
i==66 and j==0?
 
Z

Zhihao Yuan

struct A
{
A() : i(66) {}
int i, j;
};

then I'd expect A{} have i==66 rather than 0 due to value init.
Yes.

i==66 and j==0?

No. j should be uninitialized according to 8.5/7.

Roughly speaking, value initialization calls a user-provided default
ctor if there's one, or zero initialize all of the members. So if you
wrote an evil default ctor like this, j should not be initialized.

This can be tested by printing:

(new A())->j

Clang-3.2 leaves j uninitialized, while g++48 initializes it to 0
(may be unintentionally?).
 
Z

Zhihao Yuan

Have you checked that gcc does indeed explicitly initialize it, rather
than it being just a case where it happens by chance to get the value 0?

It seems to be a gcc's `feature' of allocation with `new', since A().j
is uninitialized under gcc, where is a context of value-initialization
(8.5/10).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top