Bob5421
Bob5421

Reputation: 9063

Where does C++ puts local variables?

I would like to say that C++ puts local variables on stack. But let's have a look at this code:

  class MyClass
  {
     private:
         std::map<std::string, std::pair<int, std::string> > data;

     public:
         void push(std::string a, int b, std::string c)
         {
            std::pair<int, std::string> temp;
            temp.first=45;
            temp.second=c;
            data[a] = temp;
         }
  };

At the end of push method call, temp variable should be deleted if this variable is on local stack. But my program works, and i do not know why. Do you think that data[a] = temp makes a copy of temp ? What should i do if i want to store pointers instead of making a copy ?

Upvotes: 0

Views: 99

Answers (2)

Mattia F.
Mattia F.

Reputation: 1740

Of course data[a] = temp; makes a copy of temp and stores it in data[a]. Since this is just a copy there is no problem.

If you store the address of temp inside data (changing its definition), then it will be a problem since it will store a dangling pointer.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234635

data[a] = temp; certainly does take a value copy of temp: the assignment operator for std::pair<int, std::string> is used for that.

In C++11 there are ways of putting stuff on a std::map that obviate this deep copy. Refer to move semantics and emplacement.

Upvotes: 4

Related Questions