Devolus
Devolus

Reputation: 22104

Would this corrupt the stack using a local variable?

In my class I have a member

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

Now I wrote a function which loads this vector with the process environment as key/value pairs. I don't need to access the members, so I don't use a map, and figured that a vector would be better, as 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 variable entry is local, I wonder what happens with the push_back(entry) when the function goes out of scope. will the objects, I put into the vector, persist, or will the destructor be called? Or even worse, will it simpley be overwritten or do I have to create a new pair object in the loop instead?

Upvotes: 4

Views: 167

Answers (1)

jogojapan
jogojapan

Reputation: 69997

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

To back this up, here is the relevant quote from the Standard (C++11, §23.2.3, in the big table on page 738 of the official edition):

a.push_back(t) [...] Appends a copy of t // Requires: T shall be CopyInsertable into X.

Here, X stands for the vector type, and t for an lvalue or constant rvalue of type T, which is the type of the member elements. So this applies to your case. (If the pair were to be created on the fly, i.e. inside the push_back(...) function call, you'd have a temporary rvalue, which means a different table row would apply and you'd get a move instead of a copy, but there would still not be any problems.)

A vector stores copies of its elements. (The only danger exists when you have a vector whose element types are defined as a pointer type, or some struct or class that has pointer members. The vector then, of course, makes copies only of the pointers, not deep copies of the content; or in the case of a struct or class type, it makes copies as defined by the copy constructor of that data type. But for a std::pair of std::string, all will work as expected.)

Upvotes: 2

Related Questions