I’m trying to pass a temporary object to another object constructor for the second object to take ownership of the generated object. My code is something like this
class A {
};
class B {
A a;
public:
B(A && _a) : a(_a) {}
void test(){ }
};
int main(int argc, const char *argv[])
{
B b(A());
b.test();
return 0;
}
but I’m getting this error that I’m not able to understand
$ g++ -std=c++0x main.cpp
main.cpp: In function 'int main(int, const char**)':
main.cpp:15:7: error: request for member 'test' in 'b', which is of non-class type 'B(A (*)())'
Perhaps it is just a silly syntax error, but in case it is not, how would you defined such constructor for taking ownership of some created resource?
Thanks
You got caught by what is known as C++’s most vexing parse. Your line
does not define an object
bof typeBinitialized with a temporary object of typeA, but declares a function namedbtaking an unnamed argument of type (pointer to a) function with no arguments and returningA(thus the type ofb‘s argument is declared as the function typeA()and decays to the pointer-to-function typeA(*)()which you can see in the error message), and returning a B.The simplest way around is to change that line to
In C++11, the best option is to use the new initializer syntax and write