考虑以下代理类:
class VertexProxy
{
public:
VertexProxy(double* x, double* y, double* z)
: x_(x), y_(y), z_(z) {}
VertexProxy(const VertexProxy& rhs)
: x_(rhs.x_), y_(rhs.y_), z_(rhs.z_) {}
// Coordinate getters
double x() const {return *x_;}
double y() const {return *y_;}
double z() const {return *z_;}
// Coordinate setters
VertexProxy& x(double val) {*x_ = val; return *this;}
VertexProxy& y(double val) {*y_ = val; return *this;}
VertexProxy& z(double val) {*z_ = val; return *this;}
VertexProxy& operator=(const VertexProxy& rhs)
{
// Should it be this
x_ = rhs.x_; y_ = rhs.y_; z_ = rhs.z_;
// or this?
*x_ = *rhs.x_; *y_ = *rhs.y_; *z_ = *rhs.z_;
return *this;
}
private:
double* x_; double* y_; double* z_;
};
我需要能够重置代理,以便它拥有不同的坐标指针(类似于 boost::shared_ptr.reset()
。此外,我希望能够分配坐标值与来自不同代理的值(即 proxy1.assign(proxy2)
)。
在我上面的类(class)中 operator=
应该是什么意思?要复制 rhs
的指针(浅拷贝)或 rhs
的值?还是我应该将 operator=
设为私有(private)并提供两个成员函数以避免 operator=
的歧义?
编辑:
好的,这是一些背景信息。我正在围绕第 3 方 GIS 库 (shapelib) 编写包装器,它将顶点坐标 (x、y、z、m) 存储在单独的数组(而不是结构数组)中。我的代理类用于使这个数组结构看起来更像一个结构数组。它与自定义顶点迭代器类协同工作,使处理顶点范围变得更加容易。
Shapelib 处理内存管理。我的代理类所做的只是为顶点数据提供不同的“ View ”。当用户使用我的代理操作顶点坐标时,它实际上操作的是 shapelib 形状对象中的顶点坐标。
最佳答案
鉴于您的复制构造函数复制了指针,为了保持一致性,您的复制赋值运算符应该分配指针。
VertexProxy& operator=(const VertexProxy& rhs)
{
x_ = rhs.x_;
y_ = rhs.y_;
z_ = rhs.z_;
return *this;
}
如果这段(诚然有问题的)代码会很不一致:
VertexProxy test( const VertexProxy& other )
{
double tmp1, tmp2, tmp3;
VertexProxy p1( &tmp1, &tmp2, &tmp3 );
p1 = other;
return p1;
}
行为不同:
VertexProxy test( const VertexProxy& other )
{
double tmp1, tmp2, tmp3; // unused
VertexProxy p1( other );
return p1;
}
关于c++ - 如何处理代理类复制赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121491/