C ++类/层次结构设计
我粗略地讲了以下层次结构
class Base {
public:
virtual int value() const = 0;
};
class Derived1 : public Base {
public:
int value() const {
return 1;
}
};
class Derived2 : public Base {
public:
int value() const {
return -1;
}
};
class Derived3 : public Base {
public:
Derived3(const Base & underlying);
int value() const {
return underlying_.value() + 10;
}
private:
const Base & underlying_;
};
Derived3::Derived3(const Base & underlying)
:underlying_(underlying) {}
还有一个用于基础对象的单例持有者。工作流程的一个分支是这样的:
1) 从holder中获取一个Derived1对象
2)使用Derived1对象实例化Derived3对象并使用它。
我处于多线程环境中,担心底层_引用_在第二个对象的生命周期内变得无效的问题。我不是多线程专家,但我相信这可能会发生。
我希望 Derived2 对象拥有底层对象的副本,但因为 Base 是抽象的,所以我不能这样做。有人可以评论这个设计并提出不同的方法吗?
补充一下,上述设计背后有两个驱动思想。 Derived3 应该被视为 Base 类型对象的转变。一种愿望是轮班轮班。另一个愿望是能够将 Derived3 对象存储在单例中以供以后使用。
I heave roughly speaking the following hierarchy
class Base {
public:
virtual int value() const = 0;
};
class Derived1 : public Base {
public:
int value() const {
return 1;
}
};
class Derived2 : public Base {
public:
int value() const {
return -1;
}
};
class Derived3 : public Base {
public:
Derived3(const Base & underlying);
int value() const {
return underlying_.value() + 10;
}
private:
const Base & underlying_;
};
Derived3::Derived3(const Base & underlying)
:underlying_(underlying) {}
There is also a singleton holder for Base objects. One branch of the workflow goes something like this:
1) Get a Derived1 object out of the holder
2) Instantiate a Derived3 object using the Derived1 object and use it.
I'm in a multithreaded environment and am worried about the problem of the underlying_ reference_ becoming invalidated during the lifetime of the second object. I am not an expert on multithreading but I believe this can happen.
I would like for Derived2 objects to own a copy of the underlying object but because Base is abstract I cant do that. Can someone comment of this design and suggest a different approach.
To add, there are two driving thoughts behind the above design. Derived3 should be though of as a shift of Base type objects. One desire is to have shifts of shifts. Another desire is to be able to store Derived3 objects in the singleton for possible use later.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试“克隆”您的课程。我的意思是,每个派生类都可以克隆自身并在其他派生类中使用此克隆。
通过此解决方案,您可以随时保留新的 Derived。不要忘记删除它。您的工厂返回一个 Base 对象,可以克隆该对象以获得新对象。
You can try to 'clone' your classes. I mean, each derived class may clone itself and use this clone in others derived.
With this solution, you can hold new Derived all time you need. Don't forget to delete it. Your factory returns a Base object that can be cloned to obtain a new one.
当您只有抽象类的指针或引用时,克隆是制作副本的常用方法。
Cloning is a common approach to making a copy when you just have a pointer or reference to an abstract class.