目的
研究在容器相关操作中,类的各种构造函数的调用时机。
试验
采用c++11编译
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class A
{
private:
int m_a;
public:
A(int a):m_a(a){cout << "Construct" << m_a << endl;};
A(const A &a){m_a = a.m_a;cout << "Copy Construct" << m_a << endl;};
A &operator=(const A &a){m_a=a.m_a;cout << "Copy Assigenment" << m_a << endl;return *this;};
A(A &&a){m_a=a.m_a; cout << "Move Construct" << m_a << endl;};
A &operator=(A &&a){m_a=a.m_a; cout << "Move Assigenment" << m_a << endl;};
~A(){cout << "Disstruct" << m_a << endl;};
};
void func(vector<A> vec){cout <<"in func"<< endl;};
int main()
{
vector<A> v1;
vector<A> v2;
v1.push_back(1);
v1.push_back(1);
cout << "-----1------" << endl;
v2.push_back(2);
v2.push_back(2);
cout << "-----2------" << endl;
// v1 = v2;
// cout << "-----3------" << endl;//copy assigenment
v1 = move(v2);
cout << "-----4------" << endl;
swap(v1, v2);
cout << "-----5------" << endl;
func(v2);
cout << "-----6------" << endl;
func(move(v2));
cout << "-----7------" << endl;
return 0;
}
现象
程序的输出:
Construct1
Move Construct1
Disstruct1
Construct1
Move Construct1
Copy Construct1
Disstruct1
Disstruct1
-----1------
Construct2
Move Construct2
Disstruct2
Construct2
Move Construct2
Copy Construct2
Disstruct2
Disstruct2
-----2------
Disstruct1
Disstruct1
-----4------
-----5------
Copy Construct2
Copy Construct2
in func
Disstruct2
Disstruct2
-----6------
in func
Disstruct2
Disstruct2
-----7------
结论
- move构造,可以降低对象拷贝的损耗
- swap操作,可以降低对象拷贝的损耗
- 使用函数的时候,如果确认参数中传入的对象在外部不再使用,那么尽可能的使用move操作。
- move的消耗可能比shared_ptr少点