[英]Returning unique_ptr or just moving object?
I have a factory that is creating objects, but I'm unsure what the best way is to return these objects. 我有一个正在创建对象的工厂,但是我不确定返回这些对象的最佳方法是什么。 I have the option to return a
unique_ptr<Trigger>
, or I could just return Trigger
that is handled by a Move constructor. 我可以选择返回
unique_ptr<Trigger>
,也可以返回由Move构造函数处理的Trigger
。 What is better practice? 什么是更好的做法? My best guess is Move because you are guaranteed an object.
我最好的猜测是Move,因为可以保证您是一个对象。
class TriggerFactory
{
public:
TriggerFactory();
~TriggerFactory();
Trigger createMyTrigger() const; // Trigger contains a move constructor
};
vs 与
class TriggerFactory
{
public:
TriggerFactory();
~TriggerFactory();
unique_ptr<Trigger> createMyTrigger() const;
};
Frequently the Factory pattern is used for polymorphism: the Factory will return a specific concrete type of some abstract type. 通常,工厂模式用于多态:工厂将返回某种抽象类型的特定具体类型。 In this case it must return a pointer to a heap-allocated instance (else the return value will get sliced).
在这种情况下,它必须返回指向堆分配实例的指针(否则返回值将被切片)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.