直接上例子,更能清楚的显示区别:
(例子参考自c++ primer 5th 课后题)
例子1:
#include<iostream>
#include<vector>
using namespace std;
struct X {
X() {
std::cout << "X()" << std::endl; }
X(const X&) {
std::cout << "X(const X&)" << std::endl; }
X& operator= (const X& x);
~ X() {
std::cout << "~X()" << std::endl; }
};
X& X::operator=(const X& x)
{
// 实际上这里没有输出
std::cout << "=X()" << std::endl;
}
void f (X& x1, X* x2)
{
vector<X> xvec;
xvec.push_back(x1);
xvec.push_back(*x2);
cout << "------- destructor in f -----" << endl;
}
int main(){
cout << "------- constructor -----" << endl;
X x1;
X *x2 = new X();
cout << "------- copy constructor -----" << endl;
f (x1, x2);
// f()结束会调用一次析构
cout << "------- destructor 1-----" << endl;
delete x2;
cout << "------- destructor 2-----" << endl;
return 0;
}
运行结果:
这里有个STL的知识点,为什么会在------- copy constructor -----之后会再拷贝一次和析构一次,因为vector容器一开始给的capable_size是1,当你push_back第二的对象时,就要重新开辟空间(一般来说是按照两倍空间扩容为2),把原来的东西拷贝过去,然后析构原来的空间,所以这里多调用了一次拷贝和析构。对应的你要push_back第三个时就会再次扩容(再次两倍空间扩容为4),大家可以自己试试,这里就不再展示。
------- constructor -----
X()
X()
------- copy constructor -----
X(const X&)
X(const X&)
X(const X&)
~X()
------- destructor in f -----
~X()
~X()
------- destructor 1-----
~X()
------- destructor 2-----
~X()
例子2:
#include<iostream>
using namespace std;
// .h文件
class HasPtr {
friend void swap