c++ - 如何将 "this"的生命周期移动到 C++ 中的另一个对象中?

标签 c++ segmentation-fault unique-ptr

我想在 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/

相关文章:

C++/cli 将 LPCSTR 转换为 System::String^

c - C中二维数组的段错误

c++ - unique_ptr 和 shared_ptr 的区别

c++ - 使用 strcat 后删除字符数组会导致段错误

c++ - 在这种情况下 unique_ptr 的行为应该是什么?

c++ - 关于 SDL_Window 和 unique_ptr 的几个问题

c++ - 如何清除 XFixes 区域

c++ - 创建一个可以导入为 "#include<myLibrary.h>"的 C 库

c++ - 如何在 Qt 中为 QTableView 对象获得正确的行高?

c++ - 将 std::unique_ptr 用于 QMainWindow 时退出时出现 QT 应用程序段错误