在VS2010中传递一个临时的unique_ptr给构造函数
Passing a temporary unique_ptr to a constructor in VS2010
我有一个类,我希望能够用一个临时的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时的链接器错误
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为