Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I destruct a structure in C++?

Tags:

c++

destructor

Is there a way to destruct a structure (not a class)?

like image 221
Ramilol Avatar asked Aug 17 '10 20:08

Ramilol


People also ask

Can we use destructor in structure?

You are allowed to include something called a destructor in a structure type definition. Any time a structured value of that type is destroyed, either automatically or explicitly, the destructor is run on the structured value first. Typically, the destructor deallocates memory.

How do you deconstruct a struct?

So if there is a way to "destruct" a class, you can use the exact same way to "destruct" a structure. So, if you have a struct s { } in your C++ program you can do this: s *v = new s(); delete v; // will call structure's destructor. Or just letting an object fall out of scope will call the destructor.

Can a struct have a destructor C++?

Implicitly-declared destructor If no user-declared prospective (since C++20) destructor is provided for a class type (struct, class, or union), the compiler will always declare a destructor as an inline public member of its class.


1 Answers

In C++ a struct is exactly the same as a class with the exception of the default visibility on members and bases. So if there is a way to "destruct" a class, you can use the exact same way to "destruct" a structure.

So, if you have a struct s { } in your C++ program you can do this:

s *v = new s();
delete v; // will call structure's destructor.
like image 73
Pablo Santa Cruz Avatar answered Sep 19 '22 01:09

Pablo Santa Cruz