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.
325
questions
4
votes
1answer
130 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
2answers
57 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
0answers
25 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
1answer
92 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
2answers
87 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-...
2
votes
1answer
101 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
1answer
40 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 ...
1
vote
1answer
62 views
What does it mean that the emplacement function adds a new element to a container via construction in place istead of via assignment?
In Item 41 from Effective Modern C++ Scott Meyers mentions this difference and its impact on the efficiency of emplacement with respect to insertion.
I have some doubts about that, but before asking ...
1
vote
0answers
72 views
Can I use an int (as opposed to a char) array as a memory arena where objects are created with placement new?
The question concerns a home-grown container template (a kind of std::array/vector hybrid) which holds an untyped array for storage. New elements are added by a push_back() member function which copy-...
1
vote
0answers
25 views
What is the difference between std::uninitialized_default_construct() and std::uninitialized_value_construct()? [duplicate]
There are two almost identical algorithms in STL:
https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct
https://en.cppreference.com/w/cpp/memory/uninitialized_value_construct
The ...
1
vote
1answer
57 views
Finding Bug in implementation of dynamic array class. Crashes after building list of strings
I have written a DynamicArray class in the past analogous to vector which worked.
I have also written as a demo, one where the performance is bad because it has only length and pointer, and has to ...
8
votes
3answers
169 views
Is modifying the internal bytes of a const object undefined behavior in case it contains another object constructed by placement new?
Consider the following example:
#include <new>
struct FunctionObject
{
int operator()() // non-const, modifies the state of this object
{
i += 1;
j += 2;
return ...
8
votes
0answers
101 views
UB when deleting storage-providing char array from free store?
The following example of usage of placement-new was provided by an earlier version of the cppreference page:
char* ptr = new char[sizeof(T)]; // allocate memory
T* tptr = new(ptr) T; // ...
0
votes
0answers
16 views
Placement-new appears to have 2 branches under gcov coverage measurement
Compiling and instrumenting the following example code with g++ -O0 --coverage -fno-exceptions -fno-inline and measuring the code coverage with gcov after runing some tests reports that the placement ...
0
votes
1answer
82 views
What makes placement new call the constructor of an object?
From here:
The Standard C++ Library provides a placement form of
operator new declared in the standard header as:
void *operator new(std::size_t, void *p) throw ();
Most C++ implementations define ...
2
votes
0answers
131 views
Were all implementations of std::vector non-portable before std::launder?
When emplace_back() is called on std::vector instance, an object is created in a previously allocated storage. This can be easily achieved with placement-new, which is perfectly portable.
But now, we ...
1
vote
1answer
67 views
Placement new depends on iostream [duplicate]
Why does placement new depend on #include <iostream>?
Sounds absurd? Well, this code only compiles if incommenting the include:
// #include <iostream>
struct Alignas { void* ptr; };
...
1
vote
1answer
81 views
Why is Dr Memory reporting freed memory errors when I haven't freed any memory?
The following code
#include <vector>
#include <string>
#include <iostream>
struct Type
{
std::string a;
};
int main()
{
std::vector<unsigned char> data;
data....
0
votes
0answers
30 views
Use of placement new in tp_new implementation in c++ python module
While looking for an answer to a different question, I can across the comment here:
Placement new would be intuitive, but sadly new (p) Class(args); performs zero initialisation before invoking the ...
7
votes
0answers
303 views
Calling `std::vector<A>::data()` on `A` with const or reference fields, before C++20
This is a followup on the answers for placement new on a class with reference field.
Calling std::vector<A>::data() on type A that has reference or const fields, returns a pointer to objects ...
0
votes
1answer
103 views
Using placement new with an std::function doesn't work
This code crashes at (*function)(). I'm running Visual Studio 2019 and compiling C++17 for Windows 10 x86_64. I've tested it on Linux with GCC (-std=c++17) and it works fine. I'm wondering if this is ...
1
vote
1answer
85 views
How does boost::serialization allocate memory when deserializing through a pointer?
In short, I'd like to know how boost::serialization allocates memory for an object when deserializing through a pointer. Below, you'll find an example of my question, clearly illustrated alongside ...
1
vote
1answer
27 views
Implementation of `boost::serialization::load_construct_data` throws a memory access violation error
I have implemented the pair boost::serialization::save_construct_data and boost::serialization::load_construct_data for a class that has no default constructor (helib::Context). Within the ...
0
votes
0answers
53 views
Placement new with different types
Is it well-defined behavior in C++ Standards to use placement new with different types and then delete[] the buffer of old type? Assume the alignment of a and size of the buffer pointed by a meet the ...
1
vote
2answers
62 views
Extra construction when using placement new with a storage class
In a situation where I want to avoid dynamic memory allocations, I'm replacing the new operator with a process that essentially uses the memory of some statically allocated object (the Storage class ...
9
votes
2answers
170 views
Variation on the type punning theme: in-place trivial construction
I know this is a pretty common subject, but as much as the typical UB is easy to find, I did not find this variant so far.
So, I am trying to formally introduce Pixel objects while avoiding an actual ...
9
votes
1answer
151 views
Is new (this) ThisClass() a bad idea?
class FooView final : public Something
{
...
void refresh()
{
this->~FooView();
new (this) FooView();
}
}
I have never seen this idiom, and it seems like it could ...
1
vote
2answers
75 views
How to avoid creating any object within the storage that a const automatic object used to occupy?
The C++ (draft) standard contains what I call the "ROMability clause" that is [basic.life]/10:
Creating a new object within the storage that a const complete object
with static, thread, or ...
6
votes
1answer
145 views
Undead objects ([basic.life]/8): why is reference rebinding (and const modification) allowed?
The "undead" clause
I call the undead clause the C++ rule that after the destruction of an object, if a new object is created at the same address, it can sometimes be considered the same object as ...
3
votes
2answers
239 views
Reusing data member storage via placement new during enclosing object's lifetime
This is a follow-up to my previous question where I seem to have made the problem more involved than I had originally intended. (See discussions in question and answer comments there.)
This question ...
1
vote
1answer
124 views
Reusing data member storage via placement new
Is it allowed to reuse storage of a non-static data member and if so under what conditions?
Consider the program
#include<new>
#include<type_traits>
using T = /*some type*/;
using U = /*...
0
votes
1answer
73 views
c++ allocator: operator new or placement new
After reading this link, I've known that placement new was too hard to use properly. Then I found std::allocator, so I thought std::allocator should have used placement new because it could separate ...
1
vote
0answers
52 views
What if destructor is not called after placement new [duplicate]
I'm learning how to use placement new in C++ and I find an example as below:
int main()
{
// buffer on stack
unsigned char buf[100];
// using placement new
Complex *pe = new (buf) ...
2
votes
2answers
121 views
Is it legal to construct data members of a struct separately?
class A;
class B;
//we have void *p pointing to enough free memory initially
std::pair<A,B> *pp=static_cast<std::pair<A,B> *>(p);
new (&pp->first) A(/*...*/);
new (&pp->...
2
votes
1answer
137 views
Should I use placement-new in a copy assignment operator
I'm creating a discriminated union-like class. I am using c++ 17, so I could technically use a std::variant, but because of the specific use-case I want the meaning of each variant to be more explicit ...
1
vote
1answer
141 views
Is it legal in c++ to construct array elements calling new in loop instead of new[]?
I'm writing array wrapper in C++ (like std::array). The motivation was to make array-wrapper a derivative of interface. This enables to pass arrays to functions without making them templated (through ...
20
votes
2answers
873 views
Is it safe to call placement new on `this` for trivial object?
I know that this question was asked several times already but I couldn't find an answer for this particular case.
Let's say I have a trivial class that doesn't own any resources and has empty ...
1
vote
2answers
157 views
Initialize array using variadic template list and placement new
I am trying to implement the following function:
template<typename T, typename... ARGUMENTS>
std::unique_ptr<T[], HeapDeleter<T[]>> allocate_array( ARGUMENTS&&... arguments )...
5
votes
2answers
152 views
What does it mean to obtain storage?
[basic.indet] p1 says:
When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object,...
4
votes
1answer
195 views
Placement new on non-pointer variables and class members
Consider the following example:
#include <iostream>
struct A {
int i;
A(int i)
{
this->i = i;
}
A &operator=(const A &a) = delete;
A(const A &...
2
votes
1answer
83 views
Is new(&*p) double; a no-op. Does therefore uninitialized_default_construct becomes no-op as well?
The STL documentation says that the (1) uninitialized_default_construct calls ::new (static_cast<void*>(std::addressof(*p))) Value;.
The only difference with (2) uninitialized_value_construct ...
1
vote
0answers
369 views
(C++ 14) Overload new operator to allocate more continuous space than object's size
The (C++14) class below has an overloaded new operator to allocate continuous memory for an object and some bytes as additional storage. The object stores the size of the additional storage in a ...
-1
votes
1answer
104 views
What does “new (ptr) mystruct;” do for a struct that has no functions?
AFAIK the statement new (p_to_obj) myclass; is used to call constructor of a class for an already allocated memory region.
Now, what does the statement new (p_to_struct_inst) mystruct; do for an ...
0
votes
1answer
133 views
Placement New on already existing object in SharedMemory
I have two programs. The first allocates a Shared-Memory file and the second reads from it.. I am using placement-new to place objects into this memory guaranteeing that the objects do NOT use new or ...
0
votes
2answers
64 views
Initializing objects with virtual functions on pre-allocated memory without placement new operator - is that possible? If not, why
Let's say there's a simple class hierarchy, and a state object that uses the derived class;
struct base_class {
int Value;
base_class() { this->Value = 1; }
virtual void Func() { ...
9
votes
1answer
196 views
Using placement new in generic programming
When using placement new in generic code to construct an object at a specified address, the usage pattern is a bit different from usual code. For example, consider this implementation of ...
2
votes
2answers
97 views
Is using a placement new as a copy assignment operator bad?
Sometimes I want to make classes/structs with const members. I realize that this is a bad idea for multiple reasons, but for the sake of argument let's pretend the only reason is that it makes a well-...
3
votes
2answers
109 views
reusing object's space by another object
I was looking to re-use allocated space within the base class from this pointer and C++ Standard does not approve. However, the wording of the standard seems to be wrong. It puts a condition "and ...
2
votes
1answer
85 views
Is const in placement new superfluous?
This problem ocorred to me while trying to implement a std::any like container.
Is the usage of const in placement new superfluous?
If not, what does it mean?
Should I use std::decay on placement ...
0
votes
0answers
31 views
What is the syntax for construct array of array using placement new?
i have trying to construct array of array for placement new.
i searching internet only manage to found construct an array using placement new. But what if i want array of array instead?
i not sure ...