Closed. This question is opinion-based。它当前不接受答案。












想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。

在8个月前关闭。



Improve this question




如果类的成员需要多态行为,则它必须是指针或引用。如果此成员是使用构造函数参数初始化的,并且应该与该类一样长,那么我将看到两个选项。

选项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();

在这种情况下,您应该在类字段中使用std::shared_ptr<Type>

09-07 06:26