C++ - autogenerated copy constructor and assignment operator gotchas

讨论了从VS10到VS12,拷贝构造函数和赋值运算符在类层次结构中行为的变化,导致在特定情况下输出异常现象。解释了此更改的原因及影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

It has been changed that the semantic of the copy constructor and the assignment operator in the relationship with class hierarhcy from vs10 to vs12...
one case of the gotchas is like this:

#include <iostream>
struct A
{
  A& operator=(const A&) { return *this; }
  template <typename T> A& operator=(const T&) // while one can argue that this is the desired semantic, B will continue to search its parent's definition if there is none provided 
  {
    std::cout << "This should not be printed" << std::endl;
    return *this;
  }
};

struct B : A { };



int _tmain(int argc, _TCHAR* argv[])
{
	  B x;
  B y;
  x = y;
 return 0;
}

 

 

You will see the output "This should not be printed" printed. but if you run the same code in VS 2012, you won't see it. 

if you change the main to this:

int _tmain(int argc, _TCHAR* argv[])
{
	 // B x;
  //B y;
  //x = y;

  A x ;
  A y ;
  y = x;
 return 0;

you will NOT see the output "This should not be printed" printed.

 

I guess it is because in VS2010, it is deemed right to go the parent's scope when resolving copy constructor or assignment operator before it auto generate the constructor or assignment operator... And now this has been changed because this is too dangerous?

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值