问题描述
正如Scott Myers所写,您可以利用C ++的类型系统中的放松来声明clone(),以返回指向所声明的实际类型的指针:
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared:
class Base
{
virtual Base* clone() const = 0;
};
class Derived : public Base
{
virtual Derived* clone() const
};
编译器检测到clone()返回指向对象类型的指针,
The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived.
希望clone()返回一个智能指针,意味着转移所有权语义,如下所示:
It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following:
class Base
{
virtual std::auto_ptr<Base> clone() const = 0;
};
class Derived : public Base
{
virtual std::auto_ptr<Derived> clone() const;
};
不幸的是,约定的松弛不适用于模板化的智能指针,编译器不允许
Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override.
所以,它似乎有两个选项:
So, it seems I am left with two options:
- 有clone()返回一个智能基础指针,并且客户端使用dynamic_cast来处理它。
这些方法中的其中一种是首选吗?
Is one of these approaches preferred? Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?
推荐答案
这取决于你的所有权转让方式吗?您的用例。如果你认为你需要在你知道的动态类型的一个派生对象上调用 clone
(记住, clone
是允许复制而没有知道动态类型),那么你应该可能返回一个哑指针并加载到智能指针在调用代码。如果没有,那么你只需要返回一个smart_ptr,所以你可以随时返回它在所有覆盖。
It depends on your use case. If you ever think you will need to call clone
on a derived object whose dynamic type you know (remember, the whole point of clone
is to allow copying without knowing the dynamic type), then you should probably return a dumb pointer and load that into a smart pointer in the calling code. If not, then you only need to return a smart_ptr and so you can feel free to return it in all overrides.
这篇关于什么是C ++中clone()的最好的签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!