Search code examples
c++deque

deque push back error


I am writing a compiler and use deque to store methods labels of a class and here's the sample code:

#include <deque>
#include <iostream>
#include <string>

using std::cout;
using std::deque;
using std::endl;
using std::string;

int main()
{
  deque<const char *> names;

  string prefix = "___";
  const char *classname = "Point";

  const char *methodname[] = {"Init", "PrintBoth", "PrintSelf", "equals"};

  for (int i = 0; i < 4; i++)
    {
      string label = prefix + classname + "." + methodname[i];
      names.push_back(label.c_str());
    }

  for (int i = 0; i < 4; i++)
    cout << names[i] << endl;

  return 0;
}

However, the result is not what I've expected:

___Point
___Point.PrintSelf
___Point.PrintSelf
___Point.equals

Also, I noticed if I simply push back the methodname

names.push_back(methodname[i])

I get all the methodnames in order.

What have I done wrong here?


Solution

  • for (int i = 0; i < 4; i++)
    {
      string label = prefix + classname + "." + methodname[i];
      names.push_back(label.c_str()); //what you're pushing? a temporary!
    
    } //<--- `label` is destroyed here and it's memory is freed.
    

    Here label is a variable which gets destroyed at the closing brace and gets created again, in each iteration.

    That means, what you're pushing to names is a temporary value. That is causing the problem.

    I would suggest you to use this:

    std::deque<std::string> names;
    

    then do this:

    names.push_back(label); //a copy is pushed to the deque!