在VS2010中传递一个临时的unique_ptr给构造函数

Passing a temporary unique_ptr to a constructor in VS2010

本文关键字:unique 构造函数 ptr 一个 VS2010      更新时间:2023-10-16

我有一个类,我希望能够用一个临时的unique_ptr来构造,像这样:

MyCollection foo(std::unique_ptr<MyObj>(nullptr));

对象应该获得指针的所有权。我的问题是,正确的构造函数签名是什么?

1. MyCollection(std::unique_ptr<MyObj> foo);
2. MyCollection(std::unique_ptr<MyObj>&& foo); 

第一个选项没有链接。第二个,然而,如果我这样做,然后尝试构建MyCollection与非r值会发生什么?即

std::unique_ptr<MyObj> pointer(nullptr);
MyCollection(pointer);
这里的答案是:如何将unique_ptr参数传递给构造函数或函数?建议我应该按值取unique_ptr,但正如我上面所说的,它在VS2010中没有链接(错误看起来像这样…
Error   5   error LNK2028: unresolved token (0A00075A) "private: __thiscall std::unique_ptr<class IVDSDocCore,struct std::default_delete<class IVDSDocCore> >::unique_ptr<class IVDSDocCore,struct std::default_delete<class IVDSDocCore> >(class std::unique_ptr<class IVDSDocCore,struct std::default_delete<class IVDSDocCore> > const &)" (??0?$unique_ptr@VIVDSDocCore@@U?$default_delete@VIVDSDocCore@@@std@@@std@@$$FAAE@ABV01@@Z) referenced in function "public: static void __clrcall std::unique_ptr<class IVDSDocCore,struct std::default_delete<class IVDSDocCore> >::<MarshalCopy>(class std::unique_ptr<class IVDSDocCore,struct std::default_delete<class IVDSDocCore> > *,class std::unique_ptr<class IVDSDocCore,struct std::default_delete<class IVDSDocCore> > *)" (?<MarshalCopy>@?$unique_ptr@VIVDSDocCore@@U?$default_delete@VIVDSDocCore@@@std@@@std@@$$FSMXPAV12@0@Z)  C:sviluppoFerrariGesGesDBVDS.NETVDSvdsdoc.obj

一些回复建议我需要使用移动功能。如果我使用构造函数1,并尝试这样创建对象:

如果我使用构造函数1,并尝试这样创建对象:

MyCollection foo(move(std::unique_ptr<MyObj>(nullptr)));

我得到相同的链接错误

您应该按值接受unique_ptr,这是对的,但是由于它不能被复制,您必须移到构造函数中:

MyCollection(std::unique_ptr<MyObj> foo);
//..
std::unique_ptr<MyObj> pointer(/*something*/);
MyCollection(std::move(pointer));

编辑我的错,我刚刚注意到我第一次使用构造函数时读多了。

MyCollection foo(std::unique_ptr<MyObj>(nullptr)); 
当然,如果构造函数按值接受unique_ptr,

应该可以工作。

然而,在链接器错误中提到的函数签名对我来说有点奇怪,它基本上是
void __clrcall unique_ptr<X>::<MarshalCopy>(unique_ptr<X>*, unique_ptr<X>*)

所以这可能是一个完全不同的问题。我对CLR不是很坚定,所以如果我错了,请原谅我:你在c++/CLI中使用unique_ptr吗?支持吗?<MarshalCopy>在内部做什么-看起来像生成的东西,也许它不适用于仅移动类型?

这可能与:在c++/CLI中使用unique_ptr时的链接器错误