偶到个很奇怪的问题(奇怪是因为与以前方法不一样,或者,根本就是忘记而不知道了)
代码如下:
执行完后,理所当然的感觉输出应该是:
Create tag
Create tag
Destroy tag
Destroy tag
因为函数参数传递进去时,会生成并COPY一个新的对象。生成时,自然就会调用构造函数了!
但实际上却少一个 Create tag
COPY 这个动作做了,生成这个动作没有,至少没有调用构造函数。但,在退出Add函数时,调用了析构函数。
想了想,并查了资料(有时候,看书完了,也就忘记了,所以,一定要总结)。上面函数调用时,生成了新的对象但是调用了copy constructor,而不是默认的构造函数。
A 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 。运行结果是一个必然的异常。