[英]Using std::queue with shared_ptr?
Consider the following bit of code: 考虑以下代码:
#include <queue>
#include <memory>
std::shared_ptr<char> oneSharedPtr(new char[100]);
std::queue<std::shared_ptr<char>> stringQueue;
stringQueue.queue(oneSharedPtr);
This results in 这导致
error C2274: 'function-style cast' : illegal as right side of '.' operator
Why is this? 为什么是这样? Is it safe to use shared pointers in queues (will the shared pointer's ref count go to 0 on a pop)? 在队列中使用共享指针是否安全(弹出时共享指针的ref计数将变为0)吗?
That is because std::queue has no queue
method. 这是因为std :: queue没有queue
方法。 You are probably after std::queue::push
. 您可能在std::queue::push
。
stringQueue.push(oneSharedPtr);
Note : Your use of std::shared_ptr
here is incorrect, since you are passing a newed array. 注意 :此处使用的std::shared_ptr
不正确,因为您要传递新数组。 There are a few ways to fix this: 有几种方法可以解决此问题:
1) Pass a deleter that calls delete[]
: 1)传递一个调用delete[]
:
std::shared_ptr<char> oneSharedPtr(new char[100],
[](char* buff) { delete [] buff; } );
2) Use an array-like type for which the delete
works: 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) Use boost::shared_array
3)使用boost::shared_array
boost::shared_array<char> oneSharedArray(new char[100]);
did you mean 你的意思是
#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
doesn't have queue
method. std::queue
没有queue
方法。 Use always this for example to check what is available : d 例如,始终使用此命令检查可用的内容:d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.