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 new
ing 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?
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With