osg*_*sgx 51 c++ constructor placement-new
new
如果我已经有对象的内存,我可以显式调用构造函数而不使用吗?
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
Run Code Online (Sandbox Code Playgroud)
unw*_*ind 76
有点.您可以使用placement new来使用已分配的内存来运行构造函数:
#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");
Run Code Online (Sandbox Code Playgroud)
因此,您仍在使用new
关键字,但不会进行内存分配.
Mic*_*fik 15
我想你正在寻找Placement New.在C++ FAQ精简版有你如何做一个很好的总结.这个条目有一些重要的问题:
#include <new>
使用放置新语法.Cth*_*utu 15
让我向您展示一些如何在构造和破坏方面完成的代码
#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;
Run Code Online (Sandbox Code Playgroud)
我希望上面的总结能让事情更加清晰.
归档时间: |
|
查看次数: |
29010 次 |
最近记录: |