将构造函数的参数复制到智能指针
copy parameter of a constructor into smart pointer
如果 class 的成员需要多态行为,则它需要是指针或引用。如果此成员是使用构造函数参数初始化的,并且应该与 class 一样长,我会看到两个选项。
选项1:将引用参数复制到智能指针
class A
{
private:
std::unique_ptr<Type> _ptr;
public:
A(Type& parameter) : _ptr(std::make_unique<Type>(parameter)) {}
};
选项 2:使用智能指针作为参数
class A
{
private:
std::unique_ptr<Type> _ptr;
public:
A(std::unique_ptr<Type> parameter) : _ptr(parameter) {}
};
我认为选项1的优点是调用者可以传递任何对象,而选项2不需要复制对象。
我现在的问题是,两者中哪个选项更可取?
选项 1 不好,因为您正在调用 Type
复制构造函数,因此丢失了有关真实类型的信息。
选项2可以,但是你忘了移动unique_ptr
,应该是
A(std::unique_ptr<Type> parameter) : _ptr(std::move(parameter)) {}
但是,由于您提到需要多态行为,我假设您希望以后能够像这样测试您的应用程序:
A system_under_test(fake_type);
ON_CALL(*fake_type, doSomething()).WillByDefault(Return(SomeResult));
system_under_test.run();
在这种情况下,您应该在 class 字段中使用 std::shared_ptr<Type>
。
如果 class 的成员需要多态行为,则它需要是指针或引用。如果此成员是使用构造函数参数初始化的,并且应该与 class 一样长,我会看到两个选项。
选项1:将引用参数复制到智能指针
class A
{
private:
std::unique_ptr<Type> _ptr;
public:
A(Type& parameter) : _ptr(std::make_unique<Type>(parameter)) {}
};
选项 2:使用智能指针作为参数
class A
{
private:
std::unique_ptr<Type> _ptr;
public:
A(std::unique_ptr<Type> parameter) : _ptr(parameter) {}
};
我认为选项1的优点是调用者可以传递任何对象,而选项2不需要复制对象。 我现在的问题是,两者中哪个选项更可取?
选项 1 不好,因为您正在调用 Type
复制构造函数,因此丢失了有关真实类型的信息。
选项2可以,但是你忘了移动unique_ptr
,应该是
A(std::unique_ptr<Type> parameter) : _ptr(std::move(parameter)) {}
但是,由于您提到需要多态行为,我假设您希望以后能够像这样测试您的应用程序:
A system_under_test(fake_type);
ON_CALL(*fake_type, doSomething()).WillByDefault(Return(SomeResult));
system_under_test.run();
在这种情况下,您应该在 class 字段中使用 std::shared_ptr<Type>
。