如何控制使用哪个构造函数/赋值运算符将元素插入 std::vector 类?我试图通过delete
构造我想避免使用的构造函数/赋值来做到这一点,如下所示
#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
构造函数。