I have a class, myclass
, that does not have a default constructor. I wanted to new
an array my_array
of myclass
, so here is what I did:
- I
new
ed an equally-sized arraymy_tmp_array
ofstd :: aligned_storage_t <sizeof(myclass), alignof(myclass)>
. - I looped over every item in the array, calling
new (&(my_tmp_array[i])) myclass(/*params*/);
. - I set
my_array = reinterpret_cast <myclass *> (my_tmp_array);
So far so good. Everything works nicely and all is good. Now, I naively expected that by calling delete [] my_array;
I would have successfully deleted the array, but no dice: I get a pointer being freed was not allocated
. I noticed that the value of the pointer that is actually being fed to free
is a couple of bytes smaller than that of my_array
.
I guess this has to do with the whole alignment issue, but I am confused. I expected std :: aligned_storage_t <sizeof(myclass), alignof(myclass)>
would be stored in memory just as myclass
.
Disclaimer: I am aware of the existence of std :: vectors
. I would like, however, to take the chance to learn something here. What have I done wrong?
Aucun commentaire:
Enregistrer un commentaire