[英]C++11 object composition with abstract classes
Let's say I have a class Foo that has a const member of an abstract class Bar, what is the correct way to pass Bar in the constructor to initialize the const member? 假设我有一个Foo类,它具有抽象类Bar的const成员,那么在构造函数中传递Bar来初始化const成员的正确方法是什么?
class Foo
{
public:
Foo(?Bar? bar): bar(?bar?) {};
private:
const ?Bar? bar;
}
In C++11 I was thinking of using std::unique_ptr like so: 在C ++ 11中,我正在考虑像这样使用std :: unique_ptr:
class Foo
{
public:
Foo(std::unique_ptr<Bar> &bar): bar(std::move(bar)) {};
private:
const std::unique_ptr<Bar> bar;
}
Is this the best way to do it? 这是最好的方法吗? What are the other ways and when should I use them?
还有哪些其他方式?何时应使用它们?
In... 在...
struct Foo
{
public:
Foo(std::unique_ptr<Bar> &bar): bar(std::move(bar)) {};
const std::unique_ptr<Bar> bar;
};
... bar (the pointer) is not modifiable, but the value to which is points is. ... bar(指针)不可修改,但指向的值是可修改的。
Is this what you want? 这是你想要的吗?
I would rather think: 我宁愿认为:
class Foo
{
public:
Foo(std::unique_ptr<const Bar>& bar): bar(std::move(bar)) {}
private
std::unique_ptr<const Bar> bar;
};
would be more appropriate, as not the value is truly constant. 会更合适,因为该值不是真正恒定的。 I suspect that this won't compile because the unique_ptr cannot call the destructor (specification of custom deleter springs to mind), but the value to which bar points is const, which is what you really want (I suspect).
我怀疑这不会编译,因为unique_ptr无法调用析构函数(自定义删除程序的规范浮现在脑海),但是直方图指向的值是const,这正是您真正想要的(我怀疑)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.