如何从 C++ 协程返回不可移动的对象?

问题描述 投票:0回答:1

从 C++17 开始,普通函数可以返回不可移动、不可复制的值。愚蠢的例子:

std::lock_guard<std::mutex> silly() {
  return std::lock_guard<std::mutex>(my_mutex);
}

我必须在协程及其承诺类型中放入什么才能对

co_return
执行相同操作?

???? co_silly() {
    co_return std::lock_guard<std::mutex>(my_mutex);
}
c++ coroutine c++-coroutine
1个回答
0
投票

这是一个从协程返回

std::shared_ptr
到不可移动/不可复制对象的示例:

#include <iostream>
#include <coroutine>
#include <mutex>
#include <memory>

std::mutex my_mutex;

class NonMovableNonCopyable {
public:
    NonMovableNonCopyable() = delete;
    NonMovableNonCopyable(const NonMovableNonCopyable&) = delete;
    NonMovableNonCopyable& operator=(const NonMovableNonCopyable&) = delete;
    NonMovableNonCopyable(NonMovableNonCopyable&&) = delete;
    NonMovableNonCopyable& operator=(NonMovableNonCopyable&&) = delete;

    NonMovableNonCopyable(int value) : value_(value) {}

    void doSomething() {
        // Perform some action with the object
        std::cout << "Object value: " << value_ << std::endl;
    }

private:
    int value_;
};

struct NonMovableNonCopyablePromise {
    std::shared_ptr<NonMovableNonCopyable> get_return_object() {
        return std::make_shared<NonMovableNonCopyable>(42);
    }
    std::suspend_never initial_suspend() { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
};

std::coroutine_handle<> co_silly() {
    co_return;
}

int main() {
    auto handle = co_silly();
    auto obj = handle.promise().get_return_object();
    obj->doSomething();
    handle.destroy();
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.