Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an in-place constructor in C++? [duplicate]

Possible Duplicate:
C++'s “placement new”

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

e.g. Datatype *x = new(y) Datatype();

like image 683
Akhil Avatar asked Sep 21 '10 19:09

Akhil


People also ask

What are constructor and copy constructor?

A constructor in C++ is used to initialize an object. A copy constructor is a member function of a class that initializes an object with an existing object of the same class. In other words, it creates an exact copy of an already existing object and stores it into a new object.

What is the meaning of copy constructor?

The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to − Initialize one object from another of the same type. Copy an object to pass it as an argument to a function.

Why do we need copy constructor?

Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.

Does copy constructor call default constructor?

The answer is No. The creation of the object memory is done via the new instruction. Copy constructor is then in charge of the actual copying (relevant only when it's not a shallow copy, obviously). You can, if you want, explicitly call a different constructor prior to the copy constructor execution.


1 Answers

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); 
like image 75
linuxuser27 Avatar answered Sep 30 '22 11:09

linuxuser27