C ++,是否可以直接调用构造函数,而无需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
9个解决方案
76 votes
有点。 您可以使用placement new来使用已分配的内存来运行构造函数:
#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");
因此,您仍在使用new关键字,但是没有发生内存分配。
unwind answered 2020-01-30T07:25:48Z
15 votes
我认为您正在寻找新的展示位置。 C ++ FAQ Lite很好地总结了您的操作方式。 此条目有一些重要的陷阱:
您应该2727147795161351168使用新的展示位置语法。
您的内存缓冲区需要针对要创建的对象正确对齐。
手动调用析构函数是您的工作。
Michael Kristofik answered 2020-01-30T07:26:24Z
15 votes
让我向您展示一些有关如何完成构造和破坏的代码
#include
// 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;
我希望以上总结能使事情变得更清楚。
Cthutu answered 2020-01-30T07:26:49Z
5 votes
从字面上来讲,不,没有“ new”关键字就无法做到。 有关使用“ new”关键字调用构造函数而无需实际分配内存的方法,请参见有关new放置的所有答案。
Ben Voigt answered 2020-01-30T07:27:10Z
2 votes
是的,当您有自己分配的缓冲区时,可以使用new放置。 Brian Bondy在一个相关的问题上有很好的回答:
“新放置”有什么用?
itsmatt answered 2020-01-30T07:27:34Z
1 votes
您可以调用析构函数,但是不会回收内存,并且您的调用等同于函数调用。 您必须记住,在析构函数的下面有两件事:根据您的规范破坏对象,并回收内存。 由于无论如何都会为堆栈上分配的对象调用dtor,因此两次调用它可能导致不确定的行为。
vehomzzz answered 2020-01-30T07:27:55Z
1 votes
是的,使用new放置-如上所述,但是您可能考虑使用第二个工厂类来管理存储,即使这意味着复制对象也是如此。 对于小型对象,memcpy()通常很便宜。
Martin Beckett answered 2020-01-30T07:28:15Z
0 votes
您可以使用以下模板
template
inline void InitClass(T &t, Args... args)
{
t.~T();
new (&t) T(args...);
}
用法:
struct A
{
A() {}
A(int i) : a(i) {}
int a;
} my_value;
InitClass(my_value);
InitClass(my_value, 5);
user11258054 answered 2020-01-30T07:28:39Z
-2 votes
基于注释,这仅适用于Microsoft C ++编译器
非常简单,没有new:
imguistate = (int *)malloc(ImGui::GetInternalStateSize());
memset(imguistate, 0, ImGui::GetInternalStateSize());
((ImGuiState *)imguistate)->ImGuiState::ImGuiState();
这适用于任何类:
class SomeClass {
public:
SomeClass() {
printf("Called constructor\n");
}
};
int main () {
SomeClass *someclass = new SomeClass;
someclass->SomeClass::SomeClass(); // call constructor again
}
lama12345 answered 2020-01-30T07:29:07Z