Questions tagged [placement-new]
In C++ placement new is used to construct an object at a particular memory location or to pass additional arguments to an allocation function.
376
questions
0
votes
0
answers
72
views
Undefined behavior when creating a new object at the storage location that a const object occupies
Regarding to the C++ standard ,Creating a new object at the storage location that a const object with static, thread, or automatic storage
duration occupies or, at the storage location that such a ...
0
votes
0
answers
57
views
std::launder and undefined behaviour
I am reading the p0532r0 about std::launder and when to use to avoid UB.
There is the following example.
template <typename T>
class coreoptional
{
private:
T payload;
public:
...
0
votes
1
answer
77
views
Std::vector vs. placement new for communicating const array with size known at run-time
I have two methods for creating a list of objects at run-time which have potential downsides that I'd like to consider. Ultimately I am wondering which one more e
The criteria of my problem:
One ...
14
votes
3
answers
433
views
Why can't a placement-new expression be a constant expression?
According to [expr.const]/5.18:
An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the ...
6
votes
1
answer
197
views
Legality of using delete-expression on a pointer not obtained from usual new
I wonder if this code is legal:
delete new (operator new(1)) char;
This code does the same thing, but doesn't use delete expression on a pointer obtained from placement new:
void* p = operator new(1);...
1
vote
1
answer
73
views
std::launder reachability rules
std::launder example has this block of code:
int x2[2][10];
auto p2 = std::launder(reinterpret_cast<int(*)[10]>(&x2[0][0]));
// Undefined behavior: x2[1] would be reachable through the ...
1
vote
1
answer
97
views
Is it safe to call placement new on address of elements in std::array?
I want to reuse memory declared in std::array. So at the beginning, declare a variable:
std::array<S, 1024> pool;
Then I want destroy some elements and reuse it for other purpose:
(&pool[24]...
1
vote
1
answer
91
views
C++ using placement new causes segmentation fault in constructor
please find below code. In this code, when I use "placement new", the I see segmentation fault in constructor, I am not sure why it is causing this, since I can create normal objects. Also, ...
1
vote
1
answer
70
views
May this kind of rewrite of placement new compile?
Background
I am cleaning up a legacy codebase by applying a coding guideline for the new statement.
There is code like auto x = new(ClassName); that I rewrite to auto x = new ClassName();. It's quite ...
15
votes
4
answers
1k
views
Undefined behavior or memory leak when using placement-new
I am learning about placement-new in C++ using the books listed here. Now, to look at some examples, I came across the following snippet in one of the SO post that claims that it (the given example) ...
4
votes
2
answers
110
views
Does placement-new into the same type still require to manually call the destructor?
Context
I'm trying to get a grasp on the placement-new mechanism since I never have had to use it. I'm trying to understand how to properly use it out of pure curiosity.
For the question, we will ...
1
vote
0
answers
111
views
Why am I getting an error about placement new when I'm not using placement new?
I'm getting this error:
error: exception cleanup for this placement new selects non-placement operator delete [-fpermissive]
ptrCpMsgHandler = new cpMsgHandler;
Isn't this just a plain old 'new'? ...
2
votes
1
answer
116
views
Is placement new on a const variable with automatic storage duration legal? [duplicate]
Is the following code legal according to the standard?
#include <new>
int main() {
const int x = 3;
new ((void *)&x) int { 15 };
}
It seems to me that as long as there is no use of ...
2
votes
1
answer
1k
views
warning: 'void operator delete(void*, std::size_t)' called on unallocated object
I am just playing with the placement-new operator. below code compiles and runs without any error on gcc version 11.2.But I am getting one warning as,
warning: 'void operator delete(void*, std::size_t)...
1
vote
5
answers
649
views
How to represent existing data as std::vector
I have to pass existing data (unsigned char memory area with known size) to the library function expecting const std::vector<std::byte>& . Is there any way to "fool" the library ...
0
votes
1
answer
87
views
C++ unusual use of placement new into NULL
In the following C++98 statement:
multiThreadService[nextBuffer] = new (NULL) MultiThreadService(binder);
Would it be correct to say:
this is "placement new",
the object will be created (...
1
vote
1
answer
69
views
Placement New U on existing T object and Manipulating it is UB?
In this link, Storage reuse section shows the following example.
void x()
{
long long n; // automatic, trivial
new (&n) double(3.14); // reuse with a different type okay
} // okay
and ...
6
votes
2
answers
254
views
When I perform placement new on trivial object, Is it guaranteed to preserve the object/value representation?
struct A
{
int x;
}
A t{};
t.x = 5;
new (&t) A;
// is it always safe to assume that t.x is 5?
assert(t.x == 5);
As far as I know, when a trivial object of class type is created, the ...
1
vote
1
answer
64
views
What is the need for MaxAlign trick when creating static singleton?
Following a snippet of code from Loki singleton implementation which shows what it calls "MaxAlign Trick". I assume it has something to do with alignment (duh!), but what's the purpose of ...
0
votes
1
answer
37
views
What happens to members of a stack-allocated class put down with placement new on scope end?
I have this (compiling) code:
#include <iostream>
#include <vector>
class Base {
std::vector<Base*> handles_;
public:
Base(Base* handle) : handles_( {handle} ) { };
};
...
4
votes
0
answers
192
views
std::launder vs placement-new reachabibility condition
std::launder has a precondition that all bytes reachable from the would-be-returned pointer are reachable through the passed pointer.
My understanding is that this is meant to allow compiler ...
4
votes
1
answer
189
views
The c++ programming language by Bjarne Stroustrup - operator new
Section "11.2.4 Overloading new" ends with:
"There is no special syntax for placement of arrays. Nor need there be since arbitrary types can be allocated by placement new. However, an ...
3
votes
0
answers
133
views
In C++, placement new and copy constructor implementing copy assignment operator, is it a good practice?
Given the code
struct Foo{
Foo(const Foo &other){
i = other.i;
};
Foo &operator=(const Foo &other){
if(this == &other){
return (*this);
}
new (this) Foo(...
0
votes
0
answers
78
views
Can we always use placement-new on same type or it may result in undefined behavior?
From what I get, it should normally be correct to use a placement-new for reconstructing a type like this:
A a;
auto aptr = new(&a) A();
So I decided to try it with a class member like this:
...
1
vote
2
answers
334
views
Reading struct/union members from a character buffer
I need to process data that is given to me as a char buffer where the actual structure of the data depends on the values of some of its fields.
More specifically, consider the following header file:
...
-1
votes
1
answer
110
views
Would using placement new make the following code valid?
I am building a buffer that will be used in a class and wanted to know if the following is valid according to the C++ standard:
#include <iostream>
#include <cstdint>
int main() {
...
2
votes
2
answers
130
views
Is it possible to use a union member as object storage?
I wonder whether we can use a union member as storage for an explicitly initialized and destructed object, such as in the following code:
struct X
{
X() { std::cout << "C"; }
~...
0
votes
2
answers
89
views
C++ placement new alignment of classes (on a SAMD21 microcontroller)
I am working on an application which is running on a SAMD21 microcontroller. For those unfamiliar with the SAMD21, it contains an ARM Cortex-M0+ processor. The specific model I am using has 32 kB of ...
1
vote
1
answer
117
views
Does storage reuse really require object destruction?
According to [basic.life/1] (bold emphasis mine):
The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
its initialization (if any) ...
2
votes
3
answers
162
views
Do we really need placement new-expressions?
I am trying to understand placement new-expressions in C++.
This Stack Overflow answer states that T* p = new T(arg); is equivalent to
void* place = operator new(sizeof(T)); // storage allocation
T* ...
0
votes
2
answers
123
views
Is using placement new with variable on the stack is correct?
Let's take a look to this code:
A a(123);
new(&a) A(124);
Test says that in this case when program is shutting down destructor ~A() will called once. So if in A we has some pointers as fields we ...
5
votes
2
answers
397
views
C++ placement new after memset
Suppose there's a struct whose constructor does not initialize all member variables:
struct Foo {
int x;
Foo() {}
}
If I memset some buffer to 0, use placement new on that buffer to create an ...
6
votes
1
answer
109
views
Is accessing a static constexpr member from a placement new a constant expression?
To clarify, is the following program well-formed?
#include <new>
char foo[32];
struct bar {
static constexpr int foobar = 42;
};
int main()
{
auto p = new (foo) bar();
...
0
votes
3
answers
103
views
Can value of buffer change after destructor executes
Code:
#include <cstdio>
#include <new>
struct Foo {
char ch;
~Foo() { ++ch; }
};
int main() {
static_assert(sizeof(Foo) == 1);
char buffer;
auto const* pc = new (&buffer) ...
3
votes
0
answers
127
views
C++ primer 5th edition: placement new
Hello I have this text from C++ primer 5th edition:
Explicit Destructor Invocation:
Just as placement new is analogous to using allocate, an explicit call to a destructor is analogous to calling ...
0
votes
1
answer
122
views
Why does placement-new call the standard placement operator new function?
A placement-new expression that takes a single argument that is a pointer to pre-allocated memory will construct an object of type T in that memory.
Why does it call the standard placement-new ...
2
votes
1
answer
227
views
What is a placement new?
I have some questions about placement new:
int x;
int* p = new(&x) int{10};
std::cout << x; // 10
When we say placement new, do we refer to new expression or operator new (function)?
void* ...
2
votes
1
answer
201
views
C++ primer 5th edition placement new
As far as I know a placement new doesn't allocate memory but instead it is a form of new operator that takes a pointer to an already allocated memory and construct an object there.
But I am so ...
0
votes
1
answer
55
views
Can I use the space of a dynamic array of some type to construct objects of other types? [duplicate]
can I use the memory of a dynamic array of integers with placement new?
int* p = new int[10]{};
std::string* pstr = new(p)std::string("Hi there");
std::cout << *pstr << std::endl;...
0
votes
4
answers
501
views
Placement-new vs new-expression
Again with placement new I've found an example on this forum like this:
char *buf = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi"); // placement new
...
3
votes
1
answer
110
views
Using operator new and placement new to create a dynamic array of non-default constructible objects
I am new to placement new so I wanted to separate allocation from initialization using it along operator new to allocate and construct an array of my user-defined type class Foo.
here is what I've ...
0
votes
1
answer
61
views
Allocate vs construct an array of ints using operator new and placement new
Hello to understand more placement new, operator new, expression delete.. and separating the initialization from construction, I've tried this example:
int main(){
int* p = static_cast<int*>...
4
votes
1
answer
179
views
Undefined behavior in std::uninitialized_default_construct example on cppreference?
In their example of std::uninitialized_default_construct:
struct S { std::string m{ "Default value" }; };
constexpr int n {3};
alignas(alignof(S)) unsigned char mem[n * sizeof(...
0
votes
2
answers
209
views
How to appropriately track memory allocations and frees in C++ with overloads to operator news and operator deletes?
Requirement: Tracking both allocations as well as deletions. Every allocation is identified with two parameters, let's call them P1 and P2 for now.
I use a globally overloaded placement new operator ...
0
votes
0
answers
48
views
Templated placement new - calling destructor
I'm creating my own vector implementation, using a template and placement new.
(If you're wondering why I'm creating a vector implementation, when the C++ library has one already, it's because I've ...
1
vote
1
answer
123
views
Is it UB to placement new &data[i] instead of data + i?
Consider the following code:
#include <string>
struct S { std::string str; };
int main() {
S *data = static_cast<S*>(operator new(sizeof(S) * 3));
new (&data[1]) S(); // (1)
...
2
votes
2
answers
155
views
Why does using placement new on reference types give me a segmentation fault, even with std::launder?
In the new C++20 standard, cpprefrence says:
a temporary bound to a reference in a reference element of an aggregate initialized using direct-initialization syntax (parentheses) as opposed to list-...
0
votes
1
answer
154
views
Placement new after cuda malloc managed memory
I have terrible errors with CUDA managed allocation. I'd like to confirm that the following code is correct:
T* x;
cudaMallocManaged(&x, sizeof(*x));
new(x) T(..)
Is placement new syntax ...
2
votes
1
answer
212
views
Is it a Bad Idea to destructor and reconstruct an object in the assignment operator? [duplicate]
I haven't programmed much since before the C++11 standard, so I'm still learning some of the newer idioms and how to use them.
I've been thinking how to write efficient assignment operators, and I ...
1
vote
1
answer
125
views
Can't add element into container<T> with emplace new if T has explicit constructor
I am writing a fixed size container type, with placement new.
When I was testing it I figured it out my "emplace_back()" like function does not compile if the type T has explicit ctor.
Here ...