f



Alignment, placement new and struct with pointer to array of POD

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 


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Daniel
12/13/2015 12:01:40 PM
comp.lang.c++.moderated 10738 articles. 1 followers. allnor (8509) is leader. Post Follow

5 Replies
482 Views

Similar Articles

[PageSpeed] 16

{ edited by mod to shorten lines to ~70 characters. -mod }

On Sunday, 13 December 2015 19:10:14 UTC+1, Daniel  wrote:
> 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]; 

I don't think it does.  Imagine a crazy system where size_t was unsigned
short which was 32 bits, pointers were 32 bits, but int was 128 bits.
sizeof(storage_type) would be 64 bits, and the ints would not be aligned
correctly.  I think you need to define:
    struct BB { struct B b; int i[1] };
    typedef typename std::aigned_storage<sizeof(B), 
        alignof(B)>::type storage_type;

    size_t length = 10;
    char* storage = new char[sizeof(storage_type)+(length-1)*sizeof(int)];
    B* pb = new(storage)B();
    auto pbb = reinterpret_cast<BB*>(storage);
    pb->p = new(&pbb->i)int[length];

    


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Martin
12/14/2015 6:52:14 AM
On Monday, December 14, 2015 at 8:00:20 AM UTC-5, Martin Bonner wrote:
> On Sunday, 13 December 2015 19:10:14 UTC+1, Daniel  wrote:

> > 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? 

> I think you need to define:
>     struct BB { struct B b; int i[1] };
>     typedef typename std::aigned_storage<sizeof(B), 
>         alignof(B)>::type storage_type;
> 
>     size_t length = 10;
>     char* storage = new char[sizeof(storage_type)+(length-1)*sizeof(int)];
>     B* pb = new(storage)B();
>     auto pbb = reinterpret_cast<BB*>(storage);
>     pb->p = new(&pbb->i)int[length];
> 
Thank you very much! that definitely helps my understanding. But did you 
mean to write BB instead of B in the typedef for storage_type?

Best regards,
Daniel


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Daniel
12/15/2015 7:08:29 AM
On Tuesday, 15 December 2015 14:10:17 UTC+1, Daniel  wrote:
> On Monday, December 14, 2015 at 8:00:20 AM UTC-5, Martin Bonner wrote:
> > On Sunday, 13 December 2015 19:10:14 UTC+1, Daniel  wrote:
> 
> > > 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? 
> 
> > I think you need to define:
> >     struct BB { struct B b; int i[1] };
> >     typedef typename std::aigned_storage<sizeof(B), 
> >         alignof(B)>::type storage_type;
> > 
> >     size_t length = 10;
> >     char* storage = new char[sizeof(storage_type) + 
> >                                      (length-1)*sizeof(int)];
> >     B* pb = new(storage)B();
> >     auto pbb = reinterpret_cast<BB*>(storage);
> >     pb->p = new(&pbb->i)int[length];
> > 
> Thank you very much! that definitely helps my understanding. But did you 
> mean to write BB instead of B in the typedef for storage_type?

Yes!  

(and apologies to mod for failing to format correctly last time)


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Martin
12/15/2015 1:55:01 PM
On Sunday, December 13, 2015 at 12:10:14 PM UTC-6, Daniel wrote:
> 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? 
> 
Wouldn't using std::aligned_union:

http://www.cplusplus.com/reference/type_traits/aligned_union/

be simpler?  IOW:

  using storage_type = aligned_union<Len,A,B>::type;

The only thing that needs to be calculated would be the Len
template parameter, which would just be the max of
the sizeof B and A.
 
HTH.

-regards,
Larry


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
evansl
1/11/2016 6:46:35 AM
On Monday, January 11, 2016 at 6:50:17 AM UTC-6, evansl wrote:
> On Sunday, December 13, 2015 at 12:10:14 PM UTC-6, Daniel wrote:
> > 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? 
> > 
> Wouldn't using std::aligned_union:
> 
> http://www.cplusplus.com/reference/type_traits/aligned_union/
> 
> be simpler?  IOW:
> 
>   using storage_type = aligned_union<Len,A,B>::type;
> 
> The only thing that needs to be calculated would be the Len
> template parameter, which would just be the max of
> the sizeof B and A.
[snip]
OOPS.  The Len parameter to aligned_union must be a constant,
and it's not since it depends on length, which is a runtime
value.

Sorry for noise :(


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
evansl
1/12/2016 7:21:44 AM
Reply:

Similar Artilces:

Placement new, alignment, and struct with pointer to POD
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...

length of an array in a struct in an array of structs in a struct in an array of structs
Hello, So I have this complex data structure I've built for myself, and I'm trying to get this snippet to work: $k < scalar(@{@{@VisitArray[$i]->PSearchStructArray[$j]->ClickPathArray}}) VisitArray is an array of VisitStructs. Each VisitStruct contains an array of PSearchStructs called PSearchStructArray. Each PSearchStruct contains an array called ClickPathArray. I'm trying to get the length of ClickPathArray out. I've tried numerous variations of that line, and none of them work. I do know that scalar(@{@VisitArray[$i]->PSearchStructArray}) will return the...

Array of structs instead of an array with pointers to structs?
Why make an array of pointers to structs, when it is possible to just make an array of structs? I have this struct: struct test { int a; int b; }; I have then made an array: struct test testarray[5]; I would then like to shift all the elements one index to the right and afterwards insert a new pkt struct at index 0. something like this: I would like to insert 3 different test structs with "b": 10, 20, and 30. When I iterate through the testarray and make a printout of testarray[i].b, I should see something like this: 10, 0, 0, 0, 0 20, 10, 0, 0, 0 30, 20, 10, 0, 0 ...

Struct pointer vs. struct array pointer
Say I'm using a standard windows RECT structure... RECT *prect; // I can write prect->left = 0; // but I can also write prect[-1].left = 0; prect[0].left = 0; prect[1].left = 0; and the compiler won't complain... So, what did I define in the first line, a pointer to ONE structure or a pointer to an ARRAY of structures? How can I define a pointer to an array? I don't know in advance how many RECTs there will be in the array. I'm asking because I can't make WinDbg (nor MSVC debuffer) to show me the whole array of RECTs. Thanks On Wednesday,...

Array of pointer and pointer of array
hi, here is my code : //learn a pointer points to functions #include<stdio.h> #include<stdlib.h> #include<math.h> double Add(double x,double y) {return (x+y);} double Sub(double x,double y) {return x-y;} double Mul(double x,double y) {return x*y;} double Div(double x,double y) {return x/y;} //double Pow(double x,double y) {return pow(x,y);} double (*functable[5])(double,double)={Add,Sub,Mul,Div,pow}; char *msgtable[5]={"Sum","Sub","Mul","Div","Pow"}; int main() { int i; double x=0,y=0; printf("inp...

difference of POD struct array and flat array
hi there! my problem: i need arrays of float-triples (math vector). i need these available in a flat float* array for batch processing (opengl). is an array of POD structs with three float members each equivalent to a flat array of floats in terms of memory layout? ie. is the following code legal? struct Vector { float v[3]; }; Vector vectors[3]; float flatVectors[3][3]; memcpy((const void*)flatVectors, (void*)vectors, sizeof(float)*9); // vectors now contains the same values in Vector::v as flatVectors i suspect that struct member alignment, as applied by compilers, forbids that k...

Pointer-to-array issues in C vs C++
About 20 days ago, "John Harrison" <john_andronicus@hotmail.com> replied to a message which I had written: > > > Q1 . What is the use of pointer to an array? > > > > It points to it. (The name of an array is also a pointer to it.) > > No, the name of an array decays to a pointer to the first element of the > array. A pointer to an array and a pointer to the first element of an array > are not the same thing. > > int a[10]; > cout << &a + 1 << endl; > cout << a + 1 << endl; > > The two statements pr...

Void Pointers to Void Pointer Arrays in C++
Ok I am writing a program in Visual C++. I have a void pointer that points to an array of void pointers. I have a variable that tells me how many elements are in the array of void pointers, but I cannot figure out how to dereference them. How do I where one element in my array of void pointers points to? Thanks in advance Brett Hello "Brett Verhagen" <kalluminati2001@yahoo.com> wrote in message news:2a17d8f5.0308052101.4361bce9@posting.google.com... > Ok I am writing a program in Visual C++. I have a void pointer that > points to an array of void pointers. I have a va...

completely predictable question about arrays of pointers to arrays of structs
I have a type of struct called a Ccfg. A Ccfg has a property called cardinality, and I am enumerating and storing possible Ccfgs for each of several cardinalities up to 5. I need to allocate enough space for the larger cardinalities as I will be generating almost 40,000 Ccfgs of cardinality 5 (but only 6 of cardinality 3, and somewhere between 150 and 200 of cardinality 4). The structs themselves are quite large and I am running into memory issues. I had been declaring a global variable struct Ccfg S[6][40000] to hold everything, but I am trying something more memory-efficie...

pointer to a member of a struct which is in turn a member of an array of structs
Hi folks -- I have a 4-long array t[ ] of of struct Targets. And a table of int * in p[ ]. I need to set up the int * entries in p[ ] such that each can reference an int in any member of the Targets t[ ] array. How to do it? Much-simplified example: 1. #include <stdio.h> 2. int main(int argc, char* argv[ ]) { 3. int ix; 4. typedef struct { int num1; int num2; int num3; } Targets; 5. Targets t[4]; 6. 7. typedef struct { int *number; } Pointers; 8. Pointers *ap; 9. Pointers p[3] = { { &t[?].num1 }, 10. ...

Array of pointer Vs Pointer to Array
Hello, Is there any performance difference in using of the following two declaration? int (*ptr)[10]; //Array of 10 int pointers int *ptr[10]; // pointer-to-array of 10. Regards, Sangeetha. In article <4fde56d3.0410080658.4d3648bf@posting.google.com>, sangeetha <sangeetha_b@india.com> wrote: >Hello, > >Is there any performance difference in using of the following two declaration? Yes. One declares an array of pointers, one declares a pointer to an array. > int (*ptr)[10]; //Array of 10 int pointers Contrary to your comment, this declares ptr as a pointer to an ...

C Array VS C++ Array??
Is there any new features added to the chapter of 'array', I read though this chapter and do not see much new items different from C language; "vib.cpp@gmail.com" <vib.cpp@gmail.com> kirjutas: > Is there any new features added to the chapter of 'array', I read > though this chapter and do not see much new items different from C > language; Don't know which book you are reading, but C arrays are to a large extent superseded by std::vector and other STL containers in C++. Paavo On Jan 5, 10:04=A0am, "vib....@gmail.com" <vib....@gma...

Pointer to array of array of const pointer
In order to let compiler catches unintended changes of a passed object in a function, we added const, for example: struct MyStruct { int Value; }; void bar(const MyStruct * const pObj) { // pObj = <address of another MyStruct object>; // pObj->Value = <some value>; } int main() { MyStruct AObj; bar(&AObj); } If uncommented the two lines in bar(), the compiler should be able to catch them. This also works for array of (const) pointers (to const): void foo(MyStruct const *const (PtrAry)[10])...

(: Pointer to struct withing pointer to struct :)
Hi everybody! I have the following code: struct Infos { char Haarfarbe[40]; int Groesse; }; struct Person { char Name[30]; char Nachname[20]; int Postleitzahl; struct * Infos MyInfos; }; First question: When I write in main: struct Person *pPerson; pPerson = malloc ( sizeof(struct Person) ); is there also memory requested for the second struct inside Person? Second question: How do I write values inside the second structure Infos? On Thu, 17 Nov 2005 08:02:23 -0800, Zero wrote: > First question: > > When I write in main: > > struc...

Web resources about - Alignment, placement new and struct with pointer to array of POD - comp.lang.c++.moderated

Structural alignment - Wikipedia, the free encyclopedia
Structural alignment of thioredoxins from humans and the fly Drosophila melanogaster . The proteins are shown as ribbons, with the human protein ...

Weekly Alignment (@WeeklyAlignment) on Twitter
Log in Sign up You are on Twitter Mobile because you are using an old version of Internet Explorer. Learn more here Weekly Alignment @ WeeklyAlignment ...

All sizes - Dysdera crocata barcode alignment - Flickr - Photo Sharing!
Flickr is almost certainly the best online photo management and sharing application in the world. Show off your favorite photos and videos to ...

AverageExplorer: Interactive Exploration and Alignment of Visual Data Collections - YouTube
Project Page: http://www.eecs.berkeley.edu/~junyanz/projects/averageExplorer/ We present an interactive framework that allows a user to rapidly ...

ACT government chooses 'wrong mode, wrong alignment' for Gungahlin tram
Even according to its own analyses, the ACT government should not be pursuing the tram line to Gungahlin.

New Constitution Avenue alignment to be overhauled for light rail
A proposed light rail extension to the Defence precinct at Russell would replace a dedicated bus lane currently being added to Constitution Avenue ...

Planetary alignment to offer view of five bright planets at once
From January 20 to February 20, the planets Mercury, Venus, Saturn, Mars and Jupiter will all appear visible to the naked eye in the early morning ...

Review: Tylt’s Alin Glass and Tech21’s Impact Shield make fancy screen protector alignment easier
... Alin Glass and Impact Shield are also available for the iPhone 5/5s.) Both of these accessories have been designed to tackle inaccurate alignment, ...

Ad Age To Host Event on Rise of CMO-CIO Alignment
... the CIO. Advertising Age and sibling publication BtoB are partnering to produce a new event, Marketing Technology: The Rise of CMO-CIO Alignment, ...

Georgia's EU alignment: Regional repercussions
In the wake of Georgia’s Association Agreement with the EU, the regional landscape of the South Caucasus is shifting.

Resources last updated: 1/24/2016 9:26:44 PM