Create an object in memory pointed to by a void pointer

If I have void * for some piece of free memory, and I know that at least sizeof (T) is available, is there a way to create an object of type T in this place in memory?

I was going to create a T object on the stack and memcpy it, but there seems to be a more elegant way to do this?

+5
source share
2 answers

Use a new placement for him:

#include <new>

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

Remember to delete it before freeing up memory:

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

Do not create an object on the stack and memcpy it; it is unsafe, what if the object has its address stored in the member or member?

+8
source

-, , sizeof(T) , . , , void , . .

, , , . , . :

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

All Articles