Re: [OT] Re: Teaching new tricks to an old dog (C++ -->Ada)

From: Ioannis Vranos (ivr_at_remove.this.grad.com)
Date: 03/30/05


Date: Wed, 30 Mar 2005 15:38:33 +0300

Ioannis Vranos wrote:

> Perhaps you are right. If you have the standard, have a look at 3.9-2,
> 3.9-4, and 3.9-5 which I think agrees with you.

For thread completeness, I am posting the portable versions of the codes, as things got
clarified in another thread:

#include <new>

class SomeClass
{
};

int main()
{
     unsigned char *array= new unsigned char[sizeof(SomeClass)];

     SomeClass *p= new(array)SomeClass;

     // ...

     p->~SomeClass();

     delete[] array;
}

#include <iostream>
#include <cstring>

class SomeClass
{
     public:

     double d;
     int i;
     float f;
     long l;
};

int main()
{
     using namespace std;

     unsigned char *array= new unsigned char[sizeof(SomeClass)];

     SomeClass obj= {1, 2, 3, 4};

     memcpy(array, &obj, sizeof(obj));

     SomeClass *p= static_cast<SomeClass *>( static_cast<void *>(array) );

     cout<<p->d<<" "<<p->i<<" "<<p->f<<" "<<p->l<<"\n";

     p->~SomeClass();

     delete[] array;
}

#include <iostream>
#include <cstring>
#include <cstddef>

class SomeClass
{
     public:

     void somefunc() const { std::cout<<"somefunc() was called!\n"; }
};

int main()
{
     using namespace std;

     SomeClass obj;

     unsigned char *p= reinterpret_cast<unsigned char *>(&obj);

     unsigned char *array= new unsigned char[sizeof(obj)];

     for(size_t i=0; i<sizeof(obj); ++i)
        array[i]= p[i];

     SomeClass *obj2= static_cast<SomeClass *>( static_cast<void *>(array) );

     obj2->somefunc();

     obj2->~SomeClass();

     delete[] array;
}

-- 
Ioannis Vranos
http://www23.brinkster.com/noicys


Relevant Pages