我一直在測試一些C++ 11的一些功能。 我遇到了r值引用和移動構造函數。C++ 11右值引用調用拷貝構造函數也
我實現了我的第一個移動構造函數,那就是:
#include <iostream>
#include <vector>
using namespace std;
class TestClass{
public:
TestClass(int s):
size(s), arr(new int[s]){
}
~TestClass(){
if (arr)
delete arr;
}
// copy constructor
TestClass(const TestClass& other):
size(other.size), arr(new int[other.size]){
std::copy(other.arr, other.arr + other.size, arr);
}
// move constructor
TestClass(TestClass&& other){
arr=other.arr;
size=other.size;
other.arr=nullptr;
other.size=0;
}
private:
int size;
int * arr;
};
int main(){
vector<TestClass> vec;
clock_t start=clock();
for(int i=0;i<500000;i++){
vec.push_back(TestClass(1000));
}
clock_t stop=clock();
cout<<stop-start<<endl;
return 0;
}
的代碼工作正常。無論如何把一個std :: cout裏面的複製構造函數,我注意到它被調用!並且很多次(移動構造函數500000次,複製構造函數524287次)。
更讓我吃驚的是,如果我從代碼註釋掉複製構造函數,整個程序會快得多,這次移動構造函數被稱爲1024287次。
任何線索?
您正在使用哪種編譯器? – doctorlove
http://coliru.stacked-crooked.com/view?id=0b61fede4fd9aef84b124760919e8ca8-4c5ca02fa47b506419b4501a6b65fb4f –
我正在使用gcc 4.8.1 –