函数参数传递方式 & copy constructor

偶到个很奇怪的问题(奇怪是因为与以前方法不一样,或者,根本就是忘记而不知道了)

代码如下:

 

执行完后,理所当然的感觉输出应该是:

Create tag

Create tag

Destroy tag

Destroy tag

 

因为函数参数传递进去时,会生成并COPY一个新的对象。生成时,自然就会调用构造函数了!

 

但实际上却少一个 Create tag

 

COPY 这个动作做了,生成这个动作没有,至少没有调用构造函数。但,在退出Add函数时,调用了析构函数。

 

想了想,并查了资料(有时候,看书完了,也就忘记了,所以,一定要总结)。上面函数调用时,生成了新的对象但是调用了copy constructor,而不是默认的构造函数。

 

 

copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).

  • A variable is declared which is initialized from another object, eg,
    Person q("Mickey"); // constructor is used to build q.
    Person r(p);        // copy constructor is used to build r.
    Person p = q;       // copy constructor is used to initialize in declaration.
    p = q;              // Assignment operator, no constructor or copy constructor.
  • A value parameter is initialized from its corresponding argument.
    f(p);               // copy constructor initializes formal value parameter.
  • An object is returned by a function.

C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes ashallow copy.

 

 

 

 

 

所以,在上面加上一句,就能查看到函数参数传递这个动作了。

 

 

有时候重写这个函数是非常必要的。如:

 

上面的代码在 struct tag中加了一个成员 int* pInt 。运行结果是一个必然的异常。

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值