仅在某些情况下具有引用外部变量的属性的类 [英] Class with attributes referencing an external variable only in some cases
问题描述
我有一个类,在特定情况下,该类的某些属性需要引用一个外部变量.我设法做到了,但是还有更好的方法吗?
I have a class where in a specific case some of its attributes need to reference an external variable. I managed to do in this way, but is there a better way?
#include "Vector.h"
class LineSeg
{
private:
Vector* a;
Vector* b;
bool owns;
public:
LineSeg(){
a = new Vector();
b = new Vector();
owns = true;
}
LineSeg(Vector ap, Vector bp){
a = new Vector(ap);
b = new Vector(bp);
owns = true;
}
LineSeg(Vector &ap, Vector &bp, bool owns){
a = ≈
b = &bp;
owns = false;
}
virtual ~LineSeg(){
if(owns){
delete a;
delete b;
}
}
};
我不能开设两个不同的班级.
I can't make two different classes.
推荐答案
在执行此类操作时(偶尔发生,尤其是对于互斥锁),我通常使用指向成员的指针.这样可以避免任何特殊处理,也避免了析构函数中的delete
.
When doing such things (happens occasionally especially for mutexes), I usually use pointer to members. This avoids any special treatment and delete
in the destructor.
#include "Vector.h"
class LineSeg
{
private:
Vector a0;
Vector b0;
Vector* a = &a0;
Vector* b = &b0;
public:
LineSeg()
{
}
LineSeg(Vector &ap, Vector &bp, bool copy) {
if( copy )
{
a0 = ap;
b0 = bp;
return;
}
a = ≈
b = &bp;
}
virtual ~LineSeg(){
}
};
但是,使用a0
和b0
仍会使用该类中的空间,尽管未使用,但使用外部引用时会增加一些内存开销.但是,这种构造很少需要,并且值得以少量的内存成本为代价.
However, this comes with some memory cost when external references are used, since a0
and b0
still use space in the class, though not used. However, such a construct is necessary rarely, and it's worth the little memory cost imo.
但是在设计方面,这种结构是有问题的,因为它可能造成混乱和危险.假设您添加了一个方法clear()
,它清除了两个Vector
成员:
But design-wise this construct is questionnable, because it is potentially confusing and dangerous. Let's say you add a method clear()
, which clears the both Vector
members:
void clear() {
a->clear();
b->clear();
}
现在,一位同事创建了LineSeg( myVector1, myVector2, false)
,并且在进行了一些计算调用myLineSeg.clear()
之后-可能会造成混乱,因为他自己的myVector1
和myVector2
被清除了.
Now a colleague creates a LineSeg( myVector1, myVector2, false)
and after some computing calls myLineSeg.clear()
- that might be pretty confusing, because his own myVector1
and myVector2
are cleared.
这就是为什么我将此限制为互斥锁之类的特殊情况,并且通常只允许使用protected
.
That's why I limit this to special cases like mutexes, and usually only allow it protected
.
在大多数其他情况下,vu1p3n0x是正确的-最好仅使用一种机制-始终复制,始终拥有所有权或使用shared_ptr
.
Im most other cases vu1p3n0x is right - it's much better to use only one mechanism - either copy always, take ownership always, or use shared_ptr
.
这篇关于仅在某些情况下具有引用外部变量的属性的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!