Using std::queue with shared_ptr?

Using std::queue with shared_ptr?

本文关键字:ptr shared with std queue Using      更新时间:2023-10-16

考虑以下代码:

#include <queue>
#include <memory>
std::shared_ptr<char> oneSharedPtr(new char[100]);
std::queue<std::shared_ptr<char>> stringQueue;
stringQueue.queue(oneSharedPtr);

结果是

error C2274: 'function-style cast' : illegal as right side of '.' operator

为什么会这样?在队列中使用共享指针是否安全(共享指针的refcount在pop上变为0)?

这是因为std::queue没有queue方法。你可能在std::queue::push后面。

stringQueue.push(oneSharedPtr);

注意:您在这里使用std::shared_ptr是不正确的,因为您正在传递一个新的数组。有几种方法可以解决这个问题:

1)传递一个删除器,调用delete[]:

std::shared_ptr<char> oneSharedPtr(new char[100], 
                                   [](char* buff) { delete [] buff; } ); 

2)使用delete工作的类数组类型:

std::shared_ptr<std::array<char,100>> oneSharedPtr1(new std::array<char,100>());
std::shared_ptr<std::vector<char>> oneSharedPtr2(new std::vector<char>);
std::shared_ptr<std::string> oneSharedPtr3(new std::string());
3)使用boost::shared_array
boost::shared_array<char> oneSharedArray(new char[100]);

你是说

#include <queue>
#include <memory>
int main(){
std::shared_ptr<char> oneSharedPtr(new char[100]);
std::queue<std::shared_ptr<char>> stringQueue;
stringQueue.push(oneSharedPtr);
}

?std::queue没有queue方法。例如,使用always来检查可用的内容:d

http://ideone.com/dx34N8