UberMongoose
UberMongoose

Reputation: 319

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

Upvotes: 3

Views: 9704

Answers (2)

juanchopanza
juanchopanza

Reputation: 227370

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]);

Upvotes: 6

4pie0
4pie0

Reputation: 29724

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. Use always this for example to check what is available : d

http://ideone.com/dx34N8

Upvotes: 0

Related Questions