返回元组时如何转移 unique_ptr 的所有权?

How do I transfer ownership of a unique_ptr when returning a tuple?

我正在尝试 return 一个元组,其中一个元素是 std::unique_ptr。我想将 unique_ptr 的所有权转让给调用者。我该怎么做?

#include <tuple>
#include <memory>
#include <iostream>

using namespace std;

class B
{
public:
    B(int i) : i_(i) {}

    int getI() const { return i_; }
private:
   int i_;
};

tuple<unique_ptr<B>, int>
getThem()
{
    unique_ptr<B> ptr(new B(10));
    return make_tuple(ptr, 50);
}

int
main(int argc, char *argv[])
{

    unique_ptr<B> b;
    int got = 0;

    tie(b, got) = getThem();

    cout << "b: " << b->getI() << endl;
    cout << "got: " << got << endl;

    return 0;
}

编译失败,因为 unique_ptr 的拷贝构造函数被删除了,原因很明显。但是如何指示我想将 unique_ptr 移动到 tie 中?

改为使用 std::move 调用移动运算符。

return make_tuple(std::move(ptr), 50);

本质上你只需要显式地将不可复制的类型移动到元组中,因此使用 std::movestd::tuple 有适当的构造函数来在内部复制和移动类型(移动在这里是合适的)。

如下;

#include <tuple>
#include <memory>
#include <iostream>

using namespace std;

class B
{
public:
    B(int i) : i_(i) {}

    int getI() const { return i_; }
private:
    int i_;
};

tuple<unique_ptr<B>, int>
getThem()
{
    unique_ptr<B> ptr(new B(10));
    return make_tuple(std::move(ptr), 50); // move the unique_ptr into the tuple
}

int
main(int argc, char *argv[])
{
    unique_ptr<B> b;
    int got = 0;

    tie(b, got) = getThem();

    cout << "b: " << b->getI() << endl;
    cout << "got: " << got << endl;

    return 0;
}