class Test {
public:
Test() {
std::cout << "constructing" << std::endl;
}
Test(Test &t) {
std::cout << "calling copy constructor" << std::endl;
}
Test(Test &&t) {
std::cout << "calling move constructor" << std::endl;
}
Test& operator=(const Test& a){
std::cout << "calling = constructor" << std::endl;
return *this;
}
};
Test* t1 = new Test();
Test* t2 (t1); // what's being called here
When passing a pointer to a constructor like t2, what constructor is called? (Or implicit conversion and then constructor?) This code just prints "constructing" as a result of t1 being constructed.
CodePudding user response:
Test* t2 (t1);
is direct-initialization. Direct-initialization considers constructors for class types, but Test*
is a pointer type, not a class type. Non-class types do not have constructors.
For a pointer type, direct-initialization with a single expression in the parenthesized initializer simply copies the value of the expression into the new pointer object (potentially after implicit conversions, which are not necessary here).
So t2
will simply have the same value as t1
, pointing to the object created with new Test();
.