在内存中创建一个由void指针指向的对象

Create an object in memory pointed to by a void pointer

本文关键字:指针 void 对象 一个 内存 创建      更新时间:2023-10-16

如果我有一个void*到一些空闲内存块,我知道至少有sizeof(T)可用,有没有办法在内存的那个位置创建一个类型为T的对象?

我只是想在堆栈上创建一个T对象,然后内存覆盖它,但似乎必须有一个更优雅的方式来做到这一点?

使用new:

#include <new>
void *space;
new(space) T();

请记住在释放内存之前删除它:

((T*)space)->~T();

不要在堆栈上创建对象并对其进行memcpy,这是不安全的,如果对象的地址存储在成员或成员的成员中怎么办?

首先,仅仅知道sizeof(T)的可用内存量是不够的。此外,您必须知道要分配的对象类型的void指针是正确对齐的。使用不对齐的指针可能会导致性能下降或应用程序崩溃,具体取决于您的平台。

然而,如果你知道自由内存和对齐是正确的,你可以使用placement new在那里构造你的对象。但是要注意,在这种情况下还必须显式地销毁它。例如:
#include <new>      // for placement new
#include <stdlib.h> // in this example code, the memory will be allocated with malloc
#include <string>   // we will allocate a std::string there
#include <iostream> // we will output it
int main()
{
  // get memory to allocate in
  void* memory_for_string = malloc(sizeof(string)); // malloc guarantees alignment
  if (memory_for_string == 0)
    return EXIT_FAILURE;
  // construct a std::string in that memory
  std::string* mystring = new(memory_for_string) std::string("Hello");
  // use that string
  *mystring += " world";
  std::cout << *mystring << std::endl;
  // destroy the string
  mystring->~string();
  // free the memory
  free(memory_for_string);
  return EXIT_SUCCESS;
}