Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False warning for placement new?

I have the following code:

#include "type_traits"
#include <new>


void foo()
{
    std::aligned_storage<10,alignof(long)> storage;
    new (&storage) int(12);
}

I have some storage defined (with length 10 bytes), and I am placement newing an int into that location

gcc 7.3 gives the following warning:

<source>:10:10: warning: placement new constructing an object of type 'int' and size '4' in a region of type 'std::aligned_storage<10, 8>' and size '1' [-Wplacement-new=]
     new (&storage) int(12);

If I am not incorrect this warning is incorrect. Am I missing something here or is this warning spurious?

like image 994
DarthRubik Avatar asked Mar 21 '18 20:03

DarthRubik


People also ask

In which cases we would need to use placement new?

Placement new allows you to construct an object in memory that's already allocated. You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance.

Does placement New allocate?

Placement new is a variation new operator in C++. Normal new operator does two things : (1) Allocates memory (2) Constructs an object in allocated memory. Placement new allows us to separate above two things. In placement new, we can pass a preallocated memory and construct an object in the passed memory.


1 Answers

std::aligned_storage is a trait with a nested type member. That type is of the correct size and alignment. The trait itself may have no data members, and therefore will get the default object size, which is 1.

So the fix is simple:

std::aligned_storage<10,alignof(long)>::type storage;
like image 89
StoryTeller - Unslander Monica Avatar answered Oct 01 '22 22:10

StoryTeller - Unslander Monica