本人按照深入理解C++11写了如下代码:
#include <iostream>
using namespace std;
class HugeMem {
public:
HugeMem(int size) : sz(size>0?size:1)
{
cout << “HugeMem:1” << endl;
c = new int[size];
}
HugeMem(const HugeMem& obj) : c(obj.c), sz(obj.sz)
{
cout << “HugeMem:2” << endl;
}
~HugeMem()
{
cout << “HugeMem:3” << endl;
delete[] c;
}
HugeMem(HugeMem&& hm) : c(hm.c), sz(hm.sz)
{
cout << “HugeMem:4” << endl;
hm.c = nullptr;
}
int *c;
int sz;
};
class Moveable
{
public:
Moveable()
: i(new int(3)), h(1024)
{
cout << “Moveable:1” << endl;
}
Moveable(const Moveable& obj) : i(obj.i), h(obj.h)
{
cout << “Moveable:2” << endl;
}
~Moveable()
{
cout << “Moveable:3” << endl;
delete i;
}
Moveable(Moveable&& m) : i(m.i), h(move(m.h))
{
cout << “Moveable:4” << endl;
m.i = nullptr;
}
int *i;
HugeMem h;
};
Moveable GetTemp()
{
Moveable tmp = Moveable();
// cout << hex << “Address:” << tmp.h.c <<endl;
return tmp;
}
int main()
{
Moveable a(move(GetTemp())); //调用1
//Moveable a(GetTemp()); //调用2
return 0;
}
调用1的输出:
HugeMem:1
Moveable:1
HugeMem:4
Moveable:4
Moveable:3
HugeMem:3
Moveable:3
HugeMem:3
调用2的输出:
HugeMem:1
Moveable:1
Moveable:3
HugeMem:3
编译环境: code-block自带的GCC编译器,版本gcc version 4.9.2 (tdm-1)
问题:
1. 为什么调用2没有触发移动构造函数呢?GetTemp()不是返回一个临时对象的嘛?不会除法Moveable的移动构造函数吗?
#include <iostream>
using namespace std;
class HugeMem {
public:
HugeMem(int size) : sz(size>0?size:1)
{
cout << “HugeMem:1” << endl;
c = new int[size];
}
HugeMem(const HugeMem& obj) : c(obj.c), sz(obj.sz)
{
cout << “HugeMem:2” << endl;
}
~HugeMem()
{
cout << “HugeMem:3” << endl;
delete[] c;
}
HugeMem(HugeMem&& hm) : c(hm.c), sz(hm.sz)
{
cout << “HugeMem:4” << endl;
hm.c = nullptr;
}
int *c;
int sz;
};
class Moveable
{
public:
Moveable()
: i(new int(3)), h(1024)
{
cout << “Moveable:1” << endl;
}
Moveable(const Moveable& obj) : i(obj.i), h(obj.h)
{
cout << “Moveable:2” << endl;
}
~Moveable()
{
cout << “Moveable:3” << endl;
delete i;
}
Moveable(Moveable&& m) : i(m.i), h(move(m.h))
{
cout << “Moveable:4” << endl;
m.i = nullptr;
}
int *i;
HugeMem h;
};
Moveable GetTemp()
{
Moveable tmp = Moveable();
// cout << hex << “Address:” << tmp.h.c <<endl;
return tmp;
}
int main()
{
Moveable a(move(GetTemp())); //调用1
//Moveable a(GetTemp()); //调用2
return 0;
}
调用1的输出:
HugeMem:1
Moveable:1
HugeMem:4
Moveable:4
Moveable:3
HugeMem:3
Moveable:3
HugeMem:3
调用2的输出:
HugeMem:1
Moveable:1
Moveable:3
HugeMem:3
编译环境: code-block自带的GCC编译器,版本gcc version 4.9.2 (tdm-1)
问题:
1. 为什么调用2没有触发移动构造函数呢?GetTemp()不是返回一个临时对象的嘛?不会除法Moveable的移动构造函数吗?
解决方案
1
那个是返回值优化
9
这是个专有名词,随便搜一下要多详细有多详细。
5
现代人要不断壮大在搜索框内输入惊人关键词的胆量。
20
http://www.cnblogs.com/liyiwen/archive/2009/12/02/1615711.html
http://www.cnblogs.com/zzj3/articles/3728902.html
http://www.cnblogs.com/zzj3/articles/3728902.html
5
vs2015表示调用了….