我正在尝试返回一个元组,其中一个元素是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
?
答案 0 :(得分:4)
使用std::move
代替调用移动运算符。
return make_tuple(std::move(ptr), 50);
答案 1 :(得分:4)
基本上,您只需要将不可复制的类型显式移动到元组中,从而使用std::move
。 std::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;
}