C ++,是否可以直接调用构造函数而无需new?
如果我已经有对象的内存,我可以不使用 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
推荐答案
排序.您可以使用 placement new 使用已分配的内存运行构造函数:
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");
因此,您仍在使用 new
关键字,但不会进行内存分配.
So, you're still using the new
keyword, but no memory allocation takes place.
相关文章