What Is an In-Place Constructor in C++

What is an in-place constructor in C++?

This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the new operator allocate it. For example:

Foo * f = new Foo();

The above will allocate memory for you.

void * fm = malloc(sizeof(Foo));
Foo *f = new (fm) Foo();

The above will use the memory allocated by the call to malloc. new will not allocate any more. You are not, however, limited to classes. You can use a placement new operator for any type you would allocate with a call to new.

A 'gotcha' for placement new is that you should not release the memory allocated by a call to the placement new operator using the delete keyword. You will destroy the object by calling the destructor directly.

f->~Foo();

After the destructor is manually called, the memory can then be freed as expected.

free(fm);

Is there a way to do in-place member construction in C++ (without copying and destructing an object)?

A few options there, assuming your problem comes from the copy assignment:

Use a pointer type instead

Change m_member to be a Foo*, or better a std::unique_ptr<Foo>, to better match the previous behavior, and then do:

    m_member = std::make_unique<Foo>(var1, var2);

No copy, will still be destroyed at the end of your scope, and given the description of your problem, this might mean that your "Foo" resource is going to be more efficiently managed as a pointer.

You could also...

Define a move-assignment operator

Now this means you have to define the big 5, but defining a move assignment operator will let you avoid the copy.

Foo& operator=(const Foo& other)
{
// Copy the attributes you need to copy
var1_ = other.var1_;
var2_ = other.var2_;
return *this;
}

This will effectively modify Foo in-place.

Fix the copy-assignment?

Now that's now really answering your question, but an unsuspecting developer would of course expect this to not crash, and it is highly possible that this problem will appear elsewhere, as copy-assignment is present a lot when writing code, and in standard algorithms. But there are multiple reason why this might not be able to, so I let you be the judge of that!

C++, is it possible to call a constructor directly, without new?

Sort of. You can use placement new to run the constructor using already-allocated memory:

 #include <new>

Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")};
do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor

new (&ooo[0]) Object1("I'm the 3rd object in place of first");

So, you're still using the new keyword, but no memory allocation takes place.

What uses are there for 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. Instead, it might be more efficient to perform a single allocation for a chunk of memory that can hold multiple objects, even though you don't want to use all of it at once.

DevX gives a good example:

Standard C++ also supports placement
new operator, which constructs an
object on a pre-allocated buffer. This
is useful when building a memory pool,
a garbage collector or simply when
performance and exception safety are
paramount (there's no danger of
allocation failure since the memory
has already been allocated, and
constructing an object on a
pre-allocated buffer takes less time):

char *buf  = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi"); // placement new
string *q = new string("hi"); // ordinary heap allocation

You may also want to be sure there can be no allocation failure at a certain part of critical code (for instance, in code executed by a pacemaker). In that case you would want to allocate memory earlier, then use placement new within the critical section.

Deallocation in placement new

You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer. You would have to then call the destructors of your classes manually. For a good suggestion on this, please see Stroustrup's FAQ on: Is there a "placement delete"?

Why does an in-place member initialization use a copy constructor in C++11?

All references are to N3797, the C++1y current working draft. §8.5 Initializers [dcl.init]/15 states:

The initialization that occurs in the form

T x = a;

as well as in argument passing, function return, throwing an exception (15.1), handling an exception
(15.3), and aggregate member initialization (8.5.1) is called copy-initialization. [ Note: Copy-initialization may invoke a move (12.8). —end note ]

So the declaration:

std::atomic<int> a = 0;

is performing copy-initialization. According to 8.5/17:

The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.

The destination type here is std::atomic<int> and the source type is int (i.e., decltype(0)). To determine the semantics of the initialization, we have to determine which of paragraph 17's bullets applies:

  • If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).
  • If the destination type is a reference type, see 8.5.3.
  • If the destination type is an array of characters, an array of char16_t, an array of char32_t, or an array of wchar_t, and the initializer is a string literal, see 8.5.2.
  • If the initializer is (), the object is value-initialized.
  • Otherwise, if the destination type is an array, the program is ill-formed.
  • If the destination type is a (possibly cv-qualified) class type:
    • If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, ... [does not apply, source type is int]
    • Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function
      is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the
      initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the cv-unqualified
      version of the destination type. The temporary is a prvalue. The result of the call (which is the
      temporary for the constructor case) is then used to direct-initialize, according to the rules above,
      the object that is the destination of the copy-initialization. In certain cases, an implementation
      is permitted to eliminate the copying inherent in this direct-initialization by constructing the
      intermediate result directly into the object being initialized; see 12.2, 12.8.
  • ...

There we are. The initializer expression - 0 - is converted into a std::atomic<int> via the creation of a temporary object initialized with the std::atomic<int>(int) constructor. That temporary object is used to direct-initialize the original std::atomic<int> object. The other of the "(possibly cv-qualified) class type" bullets that we ignored before now applies:

  • If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

Recall that the new initializer is a prvalue std::atomic<int>. Overload resolution determines that there is no appropriate std::atomic<int> constructor that accepts a single argument std::atomic<int>&& (std::atomic<int> is not movable or copyable) and diagnoses the program as ill-formed.

For the second part of the question,

std::atomic<int> a = {0};

is again copy initialization per 8.5/15. This time, however, the very first bullet of 8.5/17 applies:

  • If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).

For list-initialization, we must look to 8.5.4/3:

List-initialization of an object or reference of type T is defined as follows:

  • If T is an aggregate, aggregate initialization is performed (8.5.1).
  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • Otherwise, if T is a specialization of std::initializer_list<E>, a prvalue initializer_list object is constructed as described below and used to initialize the object according to the rules for initialization of an object from a class of the same type (8.5).
  • Otherwise, if T is a class type, constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution (13.3, 13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed.
  • ...

std::atomic<int> is a class type, not an aggregate or initializer_list specialization, so constructors are considered. The std::atomic<int>::atomic(int) constructor will be selected as a perfect match and is used to initialize the object.

How to in-place-construct an optional aggregate?

If you can use C++20, then what you want is

std::optional<Things>{std::in_place, "jadda", "neida"};

as seen in this live example. The reason you need C++20 is that the std::in_place_t constructor uses the form of

T(std::forward<Args>(args)...)

to initialize the object, but () only works for classes that have a constructor, which Things does not. C++ was updated to fix this, and that change made it into C++20.

In C++17 you can get this code to work by providing a constructor for Things that will initialize the members. That would look like

struct Things
{
Things(const char* msg1, const char* msg2) : one(msg1), two(msg2) {}
Unmovable one;
Unmovable two;
};

int main()
{
std::optional<Things>{std::in_place, "jadda", "neida"};
}

and you can see that working in this live example


In case you were curious, the new language added to handle this in C++20 can be found in [dcl.init.general]/15.6.2.2



Related Topics



Leave a reply



Submit