Reputation: 9063
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
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
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