C++, is it possible to call a constructor directly, without new?
Can I call constructor explicitly, without using new
, if I already have a memory for object?
class Object1{
char *str;
public:
Object1(char*str1){
str=strdup(str1);
puts("ctor");
puts(str);
}
~Object1(){
puts("dtor");
puts(str);
free(str);
}
};
Object1 ooo[2] = {
Object1("I'm the first object"), Object1("I'm the 2nd")
};
do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory
Solution 1:
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.
Solution 2:
I think you're looking for Placement New. The C++ FAQ Lite has a good summary of how you do this. There are a few important gotchas from this entry:
- You're supposed to
#include <new>
to use the placement new syntax. - Your memory buffer needs to be properly aligned for the object you are creating.
- It's your job to manually call the destructor.
Solution 3:
Let me show you some code on how it can be done, both in construction and destruction
#include <new>
// Let's create some memory where we will construct the object.
MyObject* obj = (MyObject*)malloc(sizeof(MyObject));
// Let's construct the object using the placement new
new(obj) MyObject();
// Let's destruct it now
obj->~MyObject();
// Let's release the memory we used before
free(obj);
obj = 0;
I hope the above summary makes things clearer.
Solution 4:
Literally speaking, NO, you can't do it without the "new" keyword. See all the answers about placement new for the way to use the "new" keyword to call the constructor without actually allocating memory.