push_back unique_ptr 参数如何传递到共享指针的向量上

How push_back unique_ptr parameter onto vector of shared ptrs

我很难将 unique_ptr 从我的方法参数推回共享指针向量。

IFCCB.h:

private:
vector<shared_ptr<IFC>>  m_shpVectorIFC;
public:
void addElementVectorIFC(unique_ptr<IFC> rupIFC);

IFCCB.cpp:

void IFCCB::addElementVectorIFC(unique_ptr<IFC> rupIFC)
{
    m_shpVectorIFC.push_back(std::unique_ptr<IFC>(new IFContent(rupIFC)));
}

我遇到错误:

C2664: 'IFC::IFC(const IFC &)' : cannot convert argument 1 from 'std::unique_ptr>' to 'IFO *'

在这种情况下,IFO 是 IFC 的继承父级。我不确定它为什么要看那个。

我看过 vector info and shared_ptr info, as well as using unique_ptr with standard library containers

有什么想法吗?我不习惯使用 shared_ptrs 和 unique_ptrs.

根据您的附录,您将需要使用 unique_ptr::get()IFContent 构造函数提供它想要的原始指针。根据它对该指针的作用,您实际上可能需要使用 release 来防止双重删除。另外,无论如何都不需要创建中间 unique_ptr ,因为它只是要直接转换成 shared_ptr:

void IFCCB::addElementVectorIFC(unique_ptr<IFC> rupIFC)
{
    m_shpVectorIFC.push_back(std::shared_ptr<IFC>(new IFContent(rupIFC.get())));
}

问题是 push_back 接受了容器的 value_type,即 shared_ptr<IFC>,但你传递给它的是 unique_ptr<IFC> 和 [=19= 的转换] 到 shared_ptr 使用 explicit 构造函数并且只能从 unique_ptr 右值完成,因此不能将参数隐式转换为 shared_ptr.

要使其正常工作,您需要使用 std::moveunique_ptr 转换为右值,然后显式转换为 shared_ptr

unique_ptr<IFC> p;
// ...
m_shpVectorIFC.push_back(std::shared_ptr<IFC>(std::move(p)));

或者使用 emplace_back 代替,因为该函数可以使用 explicit 构造函数来构造新的容器元素:

m_shpVectorIFC.emplace_back(std::move(p)));

我不相信你创建新 unique_ptr 的代码是正确的(为什么你不能使用上面显示的任一解决方案将 rupIFC 插入容器中?)但是如果这确实是你想要做的,你得到的错误是因为你试图将 unique_ptr<IFC> 传递给 IFContent 构造函数,它采用 IFO* 而不是 unique_ptr<IFC>。要进行编译,您需要从 rupIFC:

中获取原始指针
std::unique_ptr<IFC>(new IFContent(rupIFC.get()))

然而,这可能是不安全的,因为当 rupIFC 被销毁时,您传递给 IFContent 构造函数的指针将在函数末尾被删除,所以也许您打算释放它:

std::unique_ptr<IFC>(new IFContent(rupIFC.release()))

N.B。正如 dlf 的回答所说,如果您只想立即将其转换为 shared_ptr,则创建 unique_ptr 毫无意义,因此您可以简单地执行以下操作:

m_shpVectorIFC.emplace_back(std::make_shared<IFContent>(rupIFC.release()));