ench
ench

Reputation: 202

C/C++ Value Assignment to std::queue<char*>

I'm trying to assign char* values into a queue from a loop. I keep copying the pointer rather than assigning the data itself. I feel like there's a simple answer, but I can;t find a good example.

Example

while(something) {
    next = queue.front();
    queue.pop();
    while(something) {
        /* do work */
        /* text has new value of char* */
        queue.push(text);
    }
}

This doesn't work, obviously, as when I assign a new value to text, all of the entries in queue become that new value. I need to know how to do the proper copy/assignment.

Upvotes: 1

Views: 1649

Answers (1)

Rafał Rawicki
Rafał Rawicki

Reputation: 22690

Use std::queue<std::string> instead and std::string for keeping strings.

If you are getting a char * from somewhere, you can push it to the queue of type std::queue<std::string> and the string will be constructed implicitly.

If you cannot use a std::string for any reason (although, I cannot think about any good one for simple cases), you have to:

  1. Obtain a string length (for example with strnlen).
  2. Allocate a new char array of that size
  3. Copy the contents from the current place and push the pointer for the filled array to the queue.
  4. When pulling out of the queue you have to remember about freeing the array allocated in 2.

Upvotes: 5

Related Questions