[try Beta version]
Not logged in

 
Object lifetime question

Mar 7, 2013 at 7:15am
Hi,
I am wondering, if this is correct, or not, considering the lifetime of the strings in the vector "strings". This is a simplified version of some actual code, which runs just fine, but anyway, I suspect, that the contents of the vectors is actually invalid at the point, where it is accessed (by printf in this case).

If this is correct, would it still be, if SomeStruct were a class with the same initializing list being used in the constructor? With assignments instead of the initializing list?

Would it be correct, if the objects, stored in the vector, were not strings but vectors of strings?

1
2
3
4
5
6
7
8
9
10
11
void SomeMethod() { 
 vector<SomeStruct> test;
  for(int i = 0; i < 1; ++i) {
    vector<string> strings;
    strings.push_back("test");
    vector<float> floats;
    floats.push_back(0.0);
    test.push_back(SomeStruct(strings, floats));
  }
  printf("%s\n", test[0].strings[0].c_str());
}



1
2
3
4
5
6
7
8
9
10
struct SomeStruct {
  vector<string> strings;
  vector<float> floats;

  SomeStruct(const vector<string>& strings_in,
                   vector<float> floats_in)
      : strings(strings_in),
        floats(floats_in) {
  }
};

Last edited on Mar 7, 2013 at 7:23am
Mar 7, 2013 at 7:30am
When you push_back(), you are making a copy of what you pass into the vector. That means that test[0].strings[0].c_str() does not contain residual memory which was released at the end of the for loop, but a permanent copy of whatever you had pushed into the vector before. This will not go out of scope until the vector<SomeStruct> test goes out of scope.

So you're safe!

You only have to start worrying when pointers are involved. That's why pointers are discouraged in C++.
Topic archived. No new replies allowed.