下例中,复制构造函数如果不加const会出错,error C2558: class 'Asdf' : no copy constructor available or copy constructor is declared 'explicit'。
(1)我传的asd1不是个临时对象,为什么需要const?
(2)看不出复制构造函数为什么效率比移动构造函数低。
(3)我想把对象本身加到vector中,但是不能以引用形式传?只能用指针?
用的是VS2010的编译器。
求大神详解。谢谢。
#include <iostream>
#include <vector>
using namespace std;
class Asdf
{
public:
Asdf()
{
cout << "Constructor." << endl;
}
Asdf(Asdf & asdf1) //(1)
{
cout << "Copy Constructor." << endl;
}
Asdf(Asdf && asdf1) //(2)
{
cout << "Move Constructor." << endl;
}
int aa;
};
int main()
{
/*
vector<Asdf *> vector1; //(3)
Asdf * asd1 = new Asdf();
asd1->aa = 9;
vector1.push_back(asd1);
asd1->aa = 10;
cout << vector1[0]->aa << endl;
*/
vector<Asdf> vector1;
Asdf asd1;
asd1.aa = 9;
cout << &asd1 << endl;
vector1.push_back(asd1); //(1)
vector1.push_back(move(asd1)); //(2)
asd1.aa = 10;
cout << vector1[0].aa << endl;
return 0;
}
不一定,这个跟编译器有关。。。。。。。。。。。。。。。
Asdf(Asdf && asdf1)
&& 称为逻辑与运算符。如果两个操作数都非零,则条件为真。
http://blog.csdn.net/comhaqs/article/details/38417575
C++11 核心语言功能
Visual Studio 2010
Visual Studio 2012
Visual Studio 2013
右值引用 0.1 版、1.0 版、2.0 版、2.1 版、3.0 版
2.0 版
2.1* 版
2.1* 版
第一个问题好像是因为你下面定义了vector vector1;而这需要Asdf类中有一个接受const引用的拷贝构造函数。如果没有定义vector,拷贝构造函数像你那样定义是可疑的。
第二个是用了右值引用,省去了一次临时变量开辟空间的时间
第三个,引用是要在初始化时候赋值的,vector当然不能放引用。