【发布时间】:2017-01-25 12:39:53
【问题描述】:
有一个Test类的简单例子
#include <algorithm>
#include <iterator>
#include <vector>
template <typename T>
struct MinMax { T min, max; };
template <typename T>
using TList = std::vector<T>;
template <typename T>
class Test
{
private:
const T a, b;
const MinMax <T> m;
public:
Test() : a(0), m{ 0, 0 }, b(0.0) {};
public:
T getA() const { return a; }
MinMax <T> & getMinMax() const { return m; }
T getB() const { return b; }
Test(const Test &t) : a(t.a), b(t.b), m(t.m ) {}
};
具有常量数据成员。代替构造函数,数据不会改变。我想使用 std::inserter 将测试对象的向量复制到另一个向量。我很惊讶复制构造函数不够用
int main()
{
TList <Test <double> > t1;
TList <Test <double> > t2;
Test<double> t;
t1.push_back(t);
std::copy(t2.begin(), t2.end(), std::inserter(t1, t1.begin()));
return 0;
}
出现如下编译错误(VS2015):
Error C2280 'Test<double> &Test<double>::operator =(const Test<double> &)': attempting to reference a deleted function Const
是否可以让数据成员 const 并以不同的方式执行复制(一些 hack :-))?还是必须定义运算符=,所以数据成员不能是const(不可能分配给具有const数据成员的对象)?
感谢您的帮助。
【问题讨论】:
-
不确定,试试
std::move()? -
使用 const 数据成员,复制赋值和移动赋值都不能启用(没有可怕的 const cast hack)
-
@Richard Hodges:我担心这是不可能的。谢谢。
标签: c++ c++11 copy-constructor assignment-operator inserter