Default copy constructor does not call correct base(轉) constructor

物理狂人發表於2012-04-19

Section 12.8.8 of the C++ standard specifies that a default generated copy constructor should call the copy constructors of its base members.

However, as can be seen by running the following code

struct B {
B() {}
template B(const T&) { cout << "In B(const T&)\n"; }
B(const B&) { cout << "In copy constructor\n"; }
};

struct D : B {
D() {}
};

int main() {
D d1;
D d2(d1);
}

the default copy constructor of D calls the template constructor of B instead of B's copy constructor. It appears that root of the problem is that the compiler is generating this:

D::D(const D &rhs) : B(rhs) {}

which will perform. overload resolution and pick the template constructor. Instead, the compiler needs to generate something like this:

D::D(const D &rhs) : B(static_cast(rhs)) {}

Writing the above code is also the explicit workaround for this bug.


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24104518/viewspace-721685/,如需轉載,請註明出處,否則將追究法律責任。

相關文章