簡體   English   中英

如何將不可移動和不可復制的函數返回值獲取到數組中

[英]How to get a non-moveable and non-copyable function return value into an array

我一直在嘗試使用 C++ 協程來實現協作作業調度程序。 這涉及將協程放入數組中。 但是,我收到錯誤Object of type 'Job' cannot be assigned because its copy assignment operator is implicitly deleted當我嘗試執行此Object of type 'Job' cannot be assigned because its copy assignment operator is implicitly deleted時, Object of type 'Job' cannot be assigned because its copy assignment operator is implicitly deleted 我不完全理解波紋管代碼,但我的印象是我不能只是讓 Job 可移動/可復制。

作業.h

#include <experimental/coroutine>
#include <cstddef>

class Job {
public:
    struct promise_type;
    using coro_handle = std::experimental::coroutine_handle<promise_type>;
    Job() { handle_ = NULL; } // default value to create arrays
    Job(coro_handle handle) : handle_(handle) { assert(handle); }
    Job(Job&) = delete;
    Job(Job&&) = delete;
    bool resume() {
        if (not handle_.done())
            handle_.resume();
        return handle_.done();
    }
    ~Job() { handle_.destroy(); }
private:
    coro_handle handle_;
};

struct Job::promise_type {
    using coro_handle = std::experimental::coroutine_handle<promise_type>;
    auto get_return_object() {
        return coro_handle::from_promise(*this);
    }
    auto initial_suspend() { return std::experimental::suspend_always(); }
    auto final_suspend() { return std::experimental::suspend_always(); }
    void return_void() {}
    void unhandled_exception() {
        std::terminate();
    }
};

主程序

#include "Job.h"
Job testCoro() {
    co_return;
} // Empty coro

void main() {
    Job jobList[2048];
    jobList[0] = testCoro(); // Call coro and insert it into the list of jobs, error on this line
}

來源: https : //blog.panicsoftware.com/your-first-coroutine/

我嘗試了以下方法:

  • 傳遞一個指向 Job 的指針,但它遇到了對象生命周期問題,因為如果它是在函數的堆棧上創建的並且函數退出,則會留下一個懸空指針
  • 忽略不可移動能力並強制它,導致虛假錯誤並調用 UB
  • 具有不可復制不可移動元素類型的 C++ 容器,但由於協同例程語義,我無法創建放置新運算符

編輯 1:添加 co_return

如何將不可移動和不可復制的函數返回值獲取到數組中

Job jobList[2048]; obList[0] = testCoro();

沒有辦法分配不可移動的類型。 將此類對象放入數組的唯一方法是直接初始化數組元素。 例如:

Job jobList[] {testCoro()};

如果這不是一個選項,那么您就不能使用不可移動對象的數組。

另一種數據結構是一個自定義容器,它具有大小不變的 char 存儲數組,可重復使用放置 new,如鏈接問題所示。 目前還不清楚為什么“協程語義”會阻止這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM