gpt4 book ai didi

listing_6_6.cpp 中的 c++ 编译错误来自 C++ Concurrency In Action 一书

转载 作者:行者123 更新时间:2023-11-30 02:50:05 24 4
gpt4 key购买 nike

我正在尝试编译 Anthony Williams 的“C++ Concurrency In Action”一书中的示例 listing_6.6.cpp,但它没有编译,我不明白为什么。

我是多线程的新手,但我已经检查了代码并搜索了答案,但我仍然不明白为什么它不能编译。

问题出在这个方法上:

std::unique_ptr<node> pop_head()
{
std::lock_guard<std::mutex> head_lock(head_mutex);
if (head.get() == get_tail())
{
return nullptr;
}
std::unique_ptr<node> const old_head = std::move(head);
head = std::move(old_head->next);
return old_head; // <-- here is the problem
}

错误信息是:试图引用一个已删除的函数

完整的错误信息是(我使用的是 VS 2013):

threadsafe_queue.h(34): error C2280: 'std::unique_ptr<threadsafe_queue<Message>::node,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

完整代码为:

#include <memory>
#include <mutex>

template<typename T>
class threadsafe_queue
{
private:
struct node
{
std::shared_ptr<T> data;
std::unique_ptr<node> next;
};

std::mutex head_mutex;
std::unique_ptr<node> head;
std::mutex tail_mutex;
node* tail;

node* get_tail()
{
std::lock_guard<std::mutex> tail_lock(tail_mutex);
return tail;
}

std::unique_ptr<node> pop_head()
{
std::lock_guard<std::mutex> head_lock(head_mutex);
if (head.get() == get_tail())
{
return nullptr;
}
std::unique_ptr<node> const old_head = std::move(head);
head = std::move(old_head->next);
return old_head;
}


public:
threadsafe_queue() :
head(new node), tail(head.get())
{}

threadsafe_queue(const threadsafe_queue& other) = delete;
threadsafe_queue& operator=(const threadsafe_queue& other) = delete;

std::shared_ptr<T> try_pop()
{
std::unique_ptr<node> old_head = pop_head();
return old_head ? old_head->data : std::shared_ptr<T>();
}

void push(T new_value)
{
std::shared_ptr<T> new_data(
std::make_shared<T>(std::move(new_value)));
std::unique_ptr<node> p(new node);
node* const new_tail = p.get();
std::lock_guard<std::mutex> tail_lock(tail_mutex);
tail->data = new_data;
tail->next = std::move(p);
tail = new_tail;
}
};

谢谢!

最佳答案

TLDR:您不能从 const 对象移动,即使在返回时也是如此。

选择从 const unique_ptr 初始化 pop_head 的返回值的构造函数是已删除的复制构造函数,因此编译器拒绝此程序的错误格式是正确的.如果您查看本书本身(第 161-162 页)中的 list 6.6,您会注意到有问题的 const 不存在。

关于listing_6_6.cpp 中的 c++ 编译错误来自 C++ Concurrency In Action 一书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com