我想在 C++ 中模拟 Rust bar(self, ...)
函数,所以我这样写:
class Foo;
class Bar {
public:
explicit Bar(unique_ptr<Foo> foo);
private:
unique_ptr<Foo> _foo;
};
class Foo {
public:
Bar bar() {
return Bar(unique_ptr<Foo>(this));
}
};
Bar::Bar(unique_ptr<Foo> foo) : _foo(move(foo)) {}
TEST_CASE("Convert a Foo object into a Bar object") {
Bar b = Foo().bar();
}
这个代码段会抛出一个段错误。因为 Foo()
和 b
都认为他们拥有 Foo
的实例,所以它会被清理两次。如何解决?
我会描述我想做什么。在以下代码中:
auto foo = unique_ptr<Foo>(new Foo());
Bar b = some_func(move(foo));
调用some_func
后,foo
的生命周期“转移”到some_func
,我们不能再使用foo
不再。如果 b
继承了 foo
的资源,转换器函数应该这样设计。在我的情况下,我希望 some_func
成为 foo
的实例方法。就是这样。
最佳答案
我假设您希望测试用例中的这一行有效:
Bar b = Foo().bar();
你希望它的效果是 b
得到 std::unique_ptr<Foo>
一起玩。
如果是这种情况,您将必须实现 bar
创建 Foo
的新实例,因为 Foo()
是一个临时的,它的生命周期不能以你想要的方式变得动态。你在评论中提到 Foo
无法复制,但大概可以移动:
class Foo {
public:
Bar bar() && {
return Bar(std::make_unique<Foo>(std::move(*this)));
}
};
请注意,我做了 bar
右值限定,因此不能在左值上调用它(因为它从 *this
移动)。要在左值上调用它,你必须 move
来自它:
Foo().bar(); // rvalue calls are fine
Foo f;
std::move(f).bar(); // lvalue must be moved
关于c++ - 如何将 "this"的生命周期移动到 C++ 中的另一个对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51168810/