Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 283
UberMongoose Avatar asked Feb 13 '26 04:02

UberMongoose


1 Answers

That is because std::queue has no queue method. You are probably after std::queue::push.

stringQueue.push(oneSharedPtr);

Note: Your use of std::shared_ptr here is incorrect, since you are passing a newed array. There are a few ways to fix this:

1) Pass a deleter that calls delete[]:

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

2) Use an array-like type for which the delete works:

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

boost::shared_array<char> oneSharedArray(new char[100]);
like image 114
juanchopanza Avatar answered Feb 15 '26 16:02

juanchopanza