3

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

UberMongoose
  • 319
  • 3
  • 9
  • 1
    `shared_ptr` is not used correctly in this case. It will call `delete ptr;` and not `delete[] ptr;`. You could replace your char array by a simple string... – JBL Jun 05 '13 at 09:26
  • @JBL This is a contrived example. I actually need to store a handle to a non null terminated buffer of in memory. How should one go handling such a case where the array delete should be called? Put it in a std::vector? – UberMongoose Jun 05 '13 at 09:29
  • @JBL Looks like [boost::shared_array](http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_array.htm) is the array delete replacement for std::shared_ptr. Thanks for spotting this. – UberMongoose Jun 05 '13 at 09:39
  • 1
    Just for the sake of completion. A std::shared_ptr to a std::vector would achieve as much. – UberMongoose Jun 05 '13 at 09:41
  • Well you could try to use an `std::string` and its [`c_str()`](http://www.cplusplus.com/reference/string/string/c_str/) member function. You could also use a [`shared_array`](http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_array.htm) from Boost. – JBL Jun 05 '13 at 09:41

2 Answers2

6

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]);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

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

4pie0
  • 29,204
  • 9
  • 82
  • 118