mfontanini
mfontanini

Reputation: 21900

Using operator new on non-pod structs + Initializer list

I was trying out some stuff allocating structs, which contain non-pod members, on the heap and initializing them using initializer lists. However, the compiler encountered an error on my code. This snippet reproduces it:

#include <vector>

struct A {
    int a;
};

struct B {
    int a;
    std::vector<int> b;
};

int main() {
    std::vector<int> some_vec;
    A a = {1}; // OK
    A b = A{1}; // OK
    A *c = new A{1}; // OK(leaks, NP)
    B d = {1, some_vec}; // OK
    B e = B{1, some_vec}; // OK

    B *f = new B{1, some_vec}; // Fails to compile

    B *g = new B({1, some_vec}); // OK
}

(I know that leaks, I'm aware of that, it's just a test snippet)

The line pointed out fails to compile, on GCC 4.6.3, with this error:

test.cpp: In function ‘int main()’:
test.cpp:19:29: error: no matching function for call to ‘B::B(<brace-enclosed initializer list>)’
test.cpp:19:29: note: candidates are:
test.cpp:7:8: note: B::B()
test.cpp:7:8: note:   candidate expects 0 arguments, 2 provided
test.cpp:7:8: note: B::B(const B&)
test.cpp:7:8: note:   candidate expects 1 argument, 2 provided
test.cpp:7:8: note: B::B(B&&)
test.cpp:7:8: note:   candidate expects 1 argument, 2 provided

Apparently the compiler can't initialize my struct using the provided initializer list. The strange this is that the next line after the one that produces an error, which(at far as I can see) just copies(probably moves) a B from another that was constructed using that same initializer list, does not produce any error.

Is there anything wrong I am doing? I mean, I can live using that last line on the snippet provided, but is there any reason why I can't just create a struct using operator new and an initialization list?

Upvotes: 1

Views: 648

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

The code should compile and work. I tested it with gcc 4.7.0, and it works fine, so the bug has been fixed it seems. If you read 8.5.4 List-initialization in the standard, they say List intialization can be used as the initializer in a new expression (5.3.4).

Upvotes: 2

Related Questions