繁体   English   中英

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

[英]Create an object in memory pointed to by a void pointer

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

我只是要在堆栈上创建一个T对象并将其存储起来,但似乎必须有更优雅的方法来实现它?

使用新的展示位置:

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM