queue<string&> errors

c++, data-structures, queue, reference, string

Solution

Reference types do not meet the requirements of types that can be used in standard containers. In particular they are not copyable. Note that while the referenced object can be copyable or not, the reference itself is never copyable.

The alternative is to store pointers, which are copyable.

Problem

I have this interesting situation. I have a bunch of structs that hold a string. ``` struct foo { string mStringName; } vector<foo> mFoos; ``` I also have a queue of string references ``` queue<string&> mStringQueue; ``` And finally, I have a function that accepts a const string& ``` void Bar(const string&); ``` Heres the situation. ``` //...in some loop currentFoo = mFoos[index]; // Queue up the string name. mStringQueue.push(currentFoo.mStringName); //...Later on, go through our queue and pass each one to the function. for (int queueIndex = 0; queueIndex < mStringQueue.size(); queueIndex++) { Bar(mStringQueue.front()); mStringQueue.pop(); } ``` This gives me the following compile error: error C2664: 'std::queue<_Ty>::push' : cannot convert parameter 1 from 'String' to 'String &(&)' I'm definitley having trouble wrapping my mind around string references and whatnot, so any help would be greatly appreciated

Original source