【问题标题】:c++17 correct moving resource between unique_ptr in containersc++17在容器中的unique_ptr之间正确移动资源
【发布时间】:2022-01-24 10:28:50
【问题描述】:

如何更正将资源从现有的 unique_ptr 移动到在容器中创建的另一个? 我想将一些 unique_ptr 与来自另一个 unique_ptr 的资源放入容器中。或者可能将一个 unique_ptr 从一个容器移动到另一个容器。

这里有一些创建代码:

#include <memory>
#include <map>
#include <string>

struct MyClass
{
    std::string s;
};

int main(int argc, char* argv[])
{
    std::map<std::string, MyClass> container;
    
    std::unique_ptr<MyClass> tmp = std::make_unique<MyClass>();
    tmp->s = "test string";

    auto result = container.emplace(std::piecewise_construct,
        std::make_tuple("test"),
        std::make_tuple(std::move(tmp))
    );
    return 0;
}

【问题讨论】:

  • 您不能将对象本身移动到地图上,但在您的情况下,MyClass 的成员是可移动的,因此 MyClass 将是可移动的。所以你会得到一个MyClass 类型的新对象,我知道没有任何机制可以保留该对象并让它由地图而不是 unique_ptr 管理。

标签: c++ c++17 move unique-ptr emplace


【解决方案1】:

您的地图包含MyClass,但您正试图将std::unique_ptr&lt;MyClass&gt; 移动到其中。

您需要从 std::unique_ptr 获取实例并移动它。

std::make_tuple(std::move(*tmp))
                          ^___ Dereference the unique_ptr

【讨论】:

  • 错误message : see reference to function template instantiation 'std::tuple&lt;MyClass&gt; std::make_tuple&lt;MyClass&gt;(MyClass &amp;&amp;)' being compiled
  • @Pasha Can't reproduce.
  • 在 Visual Studio 2019 中
  • 1&gt;Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\tuple(890,18): error C2440: '&lt;function-style-cast&gt;': cannot convert from '_Ty' to '_Ttype' 1&gt; with 1&gt; [ 1&gt; _Ty=MyClass 1&gt; ] 1&gt;Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\tuple(888,1): message : No constructor could take the source type, or constructor overload resolution was ambiguous 1&gt;test.cpp(144): message : see reference to function template instantiation 'std::tuple&lt;MyClass&gt; std::make_tuple&lt;MyClass&gt;(MyClass &amp;&amp;)' being compiled
  • 你是个固执的人吧……?它也可以与msvc 一起编译。你的代码中可能有更多的东西使MyClass 不可移动......如果我不得不猜测的话。我想在这里表达的一点是我不应该猜测。用正确的minimal reproducible example 更新您的问题。
猜你喜欢
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2013-01-05
  • 2014-03-05
相关资源
最近更新 更多