C++ 容器&Move&各种构造函数

目的

研究在容器相关操作中,类的各种构造函数的调用时机。

试验

采用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少点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值