c++11 move构造函数和move operator 函数 学习

先看个代码吧!!!!!!!!!!

 

#include <iostream>

using namespace std;

class A
{
public:
	A(){cout<<"construct1..............."<<endl;}
	A& operator = (const A&&) {cout<<" operator move"<<endl;}
	A(const A&&){cout<<"move construct "<<endl;}

	A& operator = (const A&){cout<<"copy operator"<<endl;}
	A(const A&){cout<<"copy construct"<<endl;}
};
int main()
{	 
	A a1 = A();  // 这里调用的到底是哪一个构造函数?
	A a2 = std::move(A()); // 调用什么呢?
	   a2 = A();//调用operator =(const A&&)
  
    A&& a = A();//只调用默认构造
	return 0;
}
$g++ -std=c++11 -o main *.cpp -fno-elide-constructors 去掉优化
$main
construct1............... move construct construct1............... move construct construct1............... operator move construct1...............

上面的代码如果注释掉9行10行结果如下

$g++ -std=c++11 -o main *.cpp  -fno-elide-constructors          去掉优化
$main
construct1...............
copy construct
construct1...............
copy construct
construct1...............
copy operator
construct1...............

上面的代码正好验证了一句话     定义了move构造函数后,拷贝构造函数默认为删除的。   不删除也不会有什么影响!!!(目前是这样)

 

 

effective modern cpp   条款17  理解特殊成员函数的生成规则

 你要记住的事
  • 特殊成员函数是那些编译器可能自己帮我们生成的函数:默认构造函数,析构函数,copy操作,move操作。
  • 只有在类中没有显式声明的move操作,copy操作和析构函数时,move操作才被自动生成。
  • 只有在类中没有显式声明的拷贝构造函数的时候,拷贝构造函数才被自动生成。只要存在move操作的声明,拷贝构造函数就会被删除(delete)。拷贝operator=和拷贝构造函数的情况类似。在有显式声明的copy操作或析构函数时,另一个copy操作能被生成,但是这种生成方法是被弃用的
  • 成员函数模板永远不会抑制特殊成员函数的生成。

 

 

 

 还未学完!!!!!!!!

posted on 2018-05-25 02:18  zhangkele  阅读(1973)  评论(0编辑  收藏  举报

导航