ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Default copy constructor does not call correct base(转) constructor

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

原创 Linux操作系统 作者:物理狂人 时间:2012-04-19 14:33:24 0 删除 编辑

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.


http://connect.microsoft.com/VisualStudio/feedback/details/423737/default-copy-constructor-does-not-call-correct-base-constructor

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/24104518/viewspace-721685/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2010-06-16

  • 博文量
    80
  • 访问量
    140195