簡體   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