简体   繁体   中英

Dynamically allocating structures with vectors in them

If I have a dynamically allocated struct with a vector in it, when does the vector go out of scope? Will the vector destructor be called when I delete the struct, or do I need to force the destructor call before deleting the struct?

When you dynamically allocate the struct, you're also allocating everything inside it. The struct and everything in it gets destroyed when the struct is deleted. The compiler takes care to make sure all the destructors are called.

The vector will stay alive until you delete your struct

struct Foo
{
   std::vector<int> X;
}

In the above case delete f will free the vector as well.

Foo* f = new Foo();
delete f;

If your Foo is defined like so.. you need to provide a destructor.

struct Foo
{
   std::vector<int> *X;
   Foo()
   { 
       X = new std::vector<int> ();
   }

   ~Foo()
   {
      delete X;
   }
}

You can pick from either of the two approaches. The best approach is to use a shared_ptr so that you don't have to worry about deleteing the struct even

You might be overthinking things. When you destroy any object, all member objects are automatically destroyed.

struct Foo
{
  Bar x;
  std::vector<int> y;
};

int main()
{
  Foo a;
  Foo * p(new Foo);
  delete p; // #2
} // #1

At point #1, a goes out of scope, so it is destroyed. This involves destroying ay and ax (in this order), and the same for the destruction of *p and p->x / p->y in #2. Whether the Foo object was allocated automatically (as in #1) or dynamically (as in #2) is immaterial; all members get cleaned up properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM