【问题标题】:Copying a std::unique_ptr of an interface [closed]复制接口的 std::unique_ptr [关闭]
【发布时间】:2023-03-08 17:05:01
【问题描述】:

我需要复制一些接口Interfacestd::unique_ptr<Interface>

This post 总结得很好,但在我的情况下它不起作用,因为Interface 没有可用的构造函数。

例子:

//Pointer to copy
std::unique_ptr<Interface> ptr = std::make_unique<Interface>();

//error: incomplete type is not allowed
std::unique_ptr<Interface> copy{ new Interface(*ptr.get().data) };

有没有办法将ptr 深度复制到copy

【问题讨论】:

  • Interface的定义是什么?
  • 找出答案。如果不知道您的代码的作用,我们将无法帮助您。
  • 如果Interface 支持复制,您可以为复制的对象创建一个新的unique_ptr。否则没有副本....
  • 如果您的类不可复制,将其隐藏在 unique_ptr 后面不会突然神奇地使其可复制。
  • 投票关闭为不清楚,因为它真的不清楚。特别是没有指定Interface,也没有指定代码所有权。

标签: c++ c++11 unique-ptr


【解决方案1】:

这是您的Interface 课程的问题,而不是unique_ptr。您的Interface 类不能基于取消引用Interface::data 的返回值来构造。

据推测,Interface 是可复制构造且非多态的。如果是,您只需复制构造它:make_unique&lt;Interface&gt;(*ptr)。如果它不是可复制构造的,那么您根本无法复制Interface。如果它是多态类型,那么您就无法正确复制它,除非该类型被明确编码为允许这样的事情。

【讨论】:

  • −1 “如果 [接口是可复制构造的],您只需复制构造它:make_unique(*ptr)”告诉 OP 使用技术他不明白的漏洞是,slice 他要复制的对象。非常糟糕的建议。
  • @Cheersandhth.-Alf:添加了关于多态类型的注释。
【解决方案2】:

添加

virtual std::unique_ptr<Interface> clone() const = 0;

Interface。在接口实现的最后一个类中实现它:

virtual std::unique_ptr<Interface> clone() const override final {
  return std::make_unique<Implementation>(*this);
}

【讨论】:

  • 我想这是可能的,但Interface 来自图书馆,我无法修改它。不过谢谢
  • 另外,真的没有理由让它成为一个成员函数。编写一个unique_ptr_clone 函数同样容易,该函数将克隆任何可复制构造的T
  • @NicolBolas:不,函数需要是虚拟的。一个单独的函数只会对对象进行切片。
  • @Cheersandhth.-Alf:或者你 SFINAE 保护它免受多态类型的影响,就像你保护不可复制构造的类型一样。
  • @NicolBolas:不,这是"interface" class。我把它链接到维基百科的文章。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2014-06-30
  • 2022-12-04
相关资源
最近更新 更多