~~~~ 今天看了一遍C++11新特性,看到了右值引用,然后做测试,确突然发现和书上说得不一样,感觉就像是g++,对类临时变量拷贝做了优化,洗面是代码加编译结果,求大佬指导。
#include <iostream>
#include <stdio.h>
using namespace std;
class A
{
public:
A():m_ptr(new int(0)){cout << "construct" << endl;}
A(const A& a):m_ptr(new int(*a.m_ptr)) //深拷贝的拷贝构造函数
{
cout << "copy construct" << endl;
}
A(A&& a) :m_ptr(a.m_ptr)
{
a.m_ptr = nullptr;
cout << "move construct" << endl;
}
~A(){ delete m_ptr;
cout << "destruct" << endl;}
private:
int* m_ptr;
};
A GetA()
{
A a = A();
cout << "------------------1---------------" << endl;
return a;
}
int main(){
A a = GetA();
A b = A(a);
A c = A(GetA());
cout << "finish" << endl;
}
编译加结果
PS F:\C++\studytest\STL\allocator> g++ -o test .\main.cpp
PS F:\C++\studytest\STL\allocator> .\test.exe
construct
------------------1---------------
copy construct
construct
------------------1---------------
finish
destruct
destruct
destruct
PS F:\C++\studytest\STL\allocator>