Daniel
2015-12-13 18:01:40 UTC
I'm trying to understand the rules for alignment with placement new.
If we have
struct A
{
size_t length;
};
my understanding (please correct me if I'm wrong) is that this results
in a
data structure that is properly aligned:
typedef typename std::aligned_storage<sizeof(A),
alignof(A)>::type storage_type;
char* storage = new char [sizeof(storage_type)];
A* pa = new(storage)A();
But what if we have
struct B
{
size_t length;
int *p;
};
and wish to allocate storage for B and p with placement new from the
same storage?
Does this satisfy alignment rules?
typedef typename std::aligned_storage<sizeof(B),
alignof(B)>::type storage_type;
size_t length = 10;
char* storage = new char
[sizeof(storage_type)+length*sizeof(int)];
B* pb = new(storage)B();
pb->p = new(storage + sizeof(storage_type))int[length];
Thanks,
Daniel
If we have
struct A
{
size_t length;
};
my understanding (please correct me if I'm wrong) is that this results
in a
data structure that is properly aligned:
typedef typename std::aligned_storage<sizeof(A),
alignof(A)>::type storage_type;
char* storage = new char [sizeof(storage_type)];
A* pa = new(storage)A();
But what if we have
struct B
{
size_t length;
int *p;
};
and wish to allocate storage for B and p with placement new from the
same storage?
Does this satisfy alignment rules?
typedef typename std::aligned_storage<sizeof(B),
alignof(B)>::type storage_type;
size_t length = 10;
char* storage = new char
[sizeof(storage_type)+length*sizeof(int)];
B* pb = new(storage)B();
pb->p = new(storage + sizeof(storage_type))int[length];
Thanks,
Daniel
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]