【问题标题】:Create an object in memory pointed to by a void pointer在 void 指针指向的内存中创建一个对象
【发布时间】:2011-11-16 00:35:19
【问题描述】:

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

我只是打算在堆栈上创建一个 T 对象并将其 memcpy ,但似乎必须有一种更优雅的方式来做到这一点?

【问题讨论】:

  • 这与模板或c++11无关

标签: c++ pointers memory-management sizeof memcpy


【解决方案1】:

使用新的展示位置:

#include <new>

void *space;
new(space) T();

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

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

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

【讨论】:

  • 太棒了!我知道必须有一个简单的方法来做到这一点。谢谢
【解决方案2】:

首先,仅知道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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2015-11-27
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多