Possible Duplicate:
C++'s “placement new”
What is an in-place constructor in C++?
e.g. Datatype *x = new(y) Datatype();
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.
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.
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.
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.
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);
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