Does C ++ complex memory persist?

If I create an object on the stack and insert it into the list, then the object loses scope (outside the for loop in the example below) will the object still exist in the list? If the list still contains the object, then the data is now invalid / possibly corrupted?

Please let me know and please explain the reasons.

Thanks JBU

class SomeObject{
public:
   AnotherObject x;
}

//And then...
void someMethod()
{
   std::list<SomeObject> my_list;
   for(int i = 0; i < SOME_NUMBER; i++)
   {
      SomeObject tmp;
      my_list.push_back(tmp);

      //after the for loop iteration, tmp loses scope
   }

   my_list.front(); //at this point will my_list be full of valid SomeObjects or will the SomeObjects no longer be valid, even if they still point to dirty data
}

EDIT: so what if it were std::list<SomeObject*> my_list; instead of a list ... in this case will it be invalid?

+3
source share
4 answers

All containers make a copy of what they store. This is a requirement that the object is available for copying and assignment if it is to be used in a container.

, , vector, list .. .


:

struct foo {};
std::vector<foo> v;

v.push_back(foo()); 
// makes a copy of the temporary, which dies at the semicolon.

, .


:

struct foo {};
std::vector<foo*> v;

{
    foo f;
    v.push_back(&f); // fine, but...
} // ...now f stops existing and...

v.front(); // ...points to a non-existent object.
+4

, .

+6

, . push_back copy.

+2

STL (, , , ) , , , , .

, , , , - , , .

0

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


All Articles