C ++,是否可以直接调用构造函数而无需new? [英] C++, is it possible to call a constructor directly, without new?
本文介绍了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.
这篇关于C ++,是否可以直接调用构造函数而无需new?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文