Can I call constructor explicitly, without using new
, if I already have a memory for object?
class Object1{
char *str;
public:
Object1(c
Sort of. You can use placement new to run the constructor using already-allocated memory:
#include
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.