Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 844
osgx Avatar asked Mar 22 '10 17:03

osgx


People also ask

Can you call the constructor directly?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.

Can constructor be call without creating object?

NO. You can't invoke a constructor without creating an object.

Can you manually call a constructor?

You can call a constructor manually with placement new.

Is constructor called with new?

Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first. Constructor functions should only be called using new .


1 Answers

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.

like image 59
unwind Avatar answered Sep 23 '22 21:09

unwind