RTEMS/GCC C++ delete structure that contains a class

Chris Johns chrisj at rtems.org
Wed Sep 19 07:36:55 UTC 2007


Brett Swimley wrote:
> Hi All,
> 
> I may be violating "best practice" coding, but I have a question 
> regarding the RTEMS delete operator.
> 
> Consider something like:
> 
> class foo
> {
> public:
>  foo() { p = new unsigned char[10]; }
> virtual ~foo() { delete[] p; }
> unsigned char* p;
> };
> 
> I understand that calling new in a class constructor may not be the best 
> coding practice, but...
> 
> Now consider a structure that contains the class:
> 
> typedef struct foo_info
> {
> foo fooinfo;
> int i;
> } FOO_INFO;
> 

I assume this is C++ code. I think this is the same as:

struct foo_info
{
  foo fooinfo;
  int i;
};

typedef foo_info FOO_INFO;

In C++ 'struct' is actually similar to 'class' where the contents of the 
struct default to public. For example:

struct foo
{
   foo() { p = new unsigned char[10]; }
   virtual ~foo() { delete[] p; }
   unsigned char* p;
};

The typedef just declares a new name for a type. That is 'foo_info' is the 
type and FOO_INFO is just another name for it.

> Now, given this code...
> 
> q = new FOO_INFO;
> 
> q->i = 0;   // For example...
> 
> delete q;
> 
> 
> It appears that the destructor for foo never gets called.  Tracing into 
> the delete operator, it is just calling free.  
> 
> Is this normal behavior?  It appears that if I change my structure 
> declaration into a class definition, the expected behavior occurs.  If 
> this is what needs to be done, I certainly can do this.
> 
> Should deleting a structure that contains a class invoke the class 
> destructor?

Yes I think it should if the destructor does need to do something. What 
actually ends up in the code depends on what happens around the code and its 
use. You have asked the code to be inlined.

It is difficult to determine if anything is actually broken without the tools 
version and target. I built an example of the code on Fedora 7 without 
optimisation options and inspecting the code showed it had the correct calls.

> 
> Thanks in advance.
> 
> Brett
> 
> _______________________________________________
> rtems-users mailing list
> rtems-users at rtems.com
> http://rtems.rtems.org/mailman/listinfo/rtems-users



More information about the users mailing list