Would it really damage the stack using a local variable?

In my class I have a member

std::vector<std::pair<std::string, std::string> > mEnvironment; 

Now I have written a function that loads this vector into the process environment as key / value pairs. I do not need to contact the members, so I do not use the map, and decided that the vector would be better, since I only iterate over it.

 void Environment::setEnvironment(char const *oEnvironment[]) { mEnvironment.clear(); if(oEnvironment == NULL) return; std::string name; std::string value; std::pair<std::string, std::string> entry; for(const char **envp = oEnvironment; *envp != NULL; envp++) { const char *env = *envp; name.clear(); value.clear(); for(env = *envp; *env != 0; env++) { if(*env == '=') { env++; break; } name += *env; } value = env; entry = std::make_pair(name, value); mEnvironment.push_back(entry); } } 

Since the entry variable is local, I wonder what happens with push_back(entry) when the function goes out of scope. Will the objects placed in the vector be saved, or will the destructor be called? Or, even worse, will it just be overwritten or do I need to create a new paired object in a loop?

+4
source share
1 answer

Nothing bad will happen, as the vector creates a copy of the pair (and each of the two lines in it).

To support this, here is the corresponding quote from the Standard (C ++ 11, ยง23.2.3, in the large table on page 738 of the official publication):

a.push_back(t) [...] Adds a copy of t // Requires: t must be CopyInsertable in X

Here X denotes a vector type and t for an lvalue or constant rvalue of type t , which is the type of member elements. So this is relevant to your case. (If the pair were created on the fly, that is, inside the call to the push_back(...) function, you would have a temporary rvalue value, which means that a different table of tables will be used, and you will get a copy instead, but there would be no problem.)

Vector stores copies of its elements. (The only danger is when you have a vector whose element types are defined as a pointer type, or some structure or class that has pointer elements. Then the vector, of course, only makes copies of the pointers, not deep copies of the contents, or in the case of a structure or class type, it creates copies defined by the copy constructor of this data type. But for std::pair of std::string everything will work as expected.)

+2
source

Source: https://habr.com/ru/post/1487709/


All Articles