在没有放置新方法的情况下,将对象分配给c ++中的预定义地址

The*_*mer -1 c++ pointers destructor placement-new

在c ++中是否可以在内存中的特定位置分配对象?我正在实现我的业余爱好os内核内存管理器,它提供void*了存储我的东西的地址,我想知道如何使用该指针在那里分配我的对象.我试过这个:

string* s = (string*)235987532//Whatever address is given.
*s = string("Hello from string\n\0");//My own string class
//This seems to call the strings destructor here even thought I am using methods from s after this in my code...
Run Code Online (Sandbox Code Playgroud)

唯一的问题是它调用字符串对象析构函数,它不应该这样做.任何帮助表示赞赏.

编辑:我不能使用placement new,因为我正在开发内核级别.

Mik*_*our 5

分配仅在已存在有效对象时才有效.要在任意内存位置创建对象,请使用placement new:

new (s) string("Hello");
Run Code Online (Sandbox Code Playgroud)

一旦你完成它,你应该使用显式的析构函数调用来销毁它

s->~string();
Run Code Online (Sandbox Code Playgroud)

更新:我刚刚注意到你的问题规定"没有新的位置".在这种情况下,答案是"你不能".