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

时间:2015-10-09 05:24:30

标签: c++ c++11 unique-ptr

我正在尝试返回一个元组,其中一个元素是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

2 个答案:

答案 0 :(得分:4)

使用std::move代替调用移动运算符。

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

答案 1 :(得分:4)

基本上,您只需要将不可复制的类型显式移动到元组中,从而使用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;
}