Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Sepples Magic

Name: Anonymous 2011-02-23 21:22


#include <string>
#include <vector>
#include <iostream>

std::vector<std::string> names;

void addNames()
{
    names.push_back(std::string("Foo"));
    names.push_back(std::string("Bar"));
}

int main(int argc, char **argv)
{
    addNames();
   
    for (int i = 0, size = names.size(); i < size; ++i)
    {
        std::cout << names[i] << std::endl;
    }

    return 0;
}


Output:

Foo
Bar


Okay so what I'm trying to understand is since I'm pushing anonymous stack string objects onto the vector, I'm assuming that the strings will also have their destructors called (because local variables). This should also destroy the internal char sequence.

Yet the strings remain intact when printing the vector (so somehow its being copied?). So /prog/ please show me your sepples mastery and explain the magic here.

Name: Anonymous 2011-02-24 5:38

>>1
Okay so what I'm trying to understand is since I'm pushing anonymous stack string objects onto the vector,

You are pushing copies of them actually. Which use copies of the string constants themselves. In other words: you have a char* constant "Foo" allocated in the program's const data area, a temporary stack-allocated string object and a heap region containing the copy of "Foo", and an element of a vector<string> holding a pointer to another heap region containing the copy of "Foo". The destruction of the temporary doesn't affect either of the others.

You now also see how C++ allows utilizing every last bit of performance of the hardware!

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List