如何控制使用哪個構造函數/賦值運算符將元素插入到std :: vector類中?我試圖做到這一點通過delete
荷蘭國際集團的構造函數/賦值我想避免使用如下使用std :: vector移動和複製語義
#include<iostream>
#include<vector>
using namespace std;
class copyer{
double d;
public:
//ban moving
copyer(copyer&& c) = delete;
copyer& operator=(copyer&& c) = delete;
//copy construction
copyer(const copyer& c){
cout << "Copy constructor!" << endl;
d = c.d;
}
copyer& copy(const copyer& c){
cout << "Copy constructor!" << endl;
d = c.d;
return *this;
}
//Constructor
copyer(double s) : d(s) { }
double fn(){return d;}
};
class mover{
double d;
public:
//ban copying
mover(const mover& c) = delete;
mover& operator=(const mover& c) = delete;
//move construction
mover(mover&& c){
cout << "Move constructor!" << endl;
d = c.d;
}
mover& copy(mover&& c){
cout << "Move constructor!" << endl;
d = c.d;
return *this;
}
//Constructor
mover(double s) : d(s) { }
double fn(){return d;}
};
template<class P> class ConstrTests{
double d;
size_t N;
std::vector<P> object;
public:
ConstrTests(double s, size_t n) : d(s) , N(n) {
object.reserve(N);
for(int i = 0; i<N; i++){
object.push_back(P((double) i*d));
}
}
void test(){
int i = 0;
while(i<N){
cout << "Testing " <<i+1 << "th object: " << object.at(i).fn();
i++;
}
}
};
當我編譯和運行
size_t N = 10;
double d = 4.0;
ConstrTests<mover> Test1 = ConstrTests<mover>(d,N);
Test1.test();
我沒有問題,但如果相反,我嘗試
size_t N = 10;
double d = 4.0;
ConstrTests<copyer> Test1 = ConstrTests<copyer>(d,N);
Test1.test();
編譯時出現錯誤,說明我試圖使用已刪除的move
構造函數。