wallacer
wallacer

Reputation: 13213

Create an object in memory pointed to by a void pointer

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

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

Upvotes: 5

Views: 891

Answers (2)

celtschk
celtschk

Reputation: 19721

First, just knowing that sizeof(T) amount of memory is available is not sufficient. In addition you must know that the void pointer is aligned correctly for the type of object you want to allocate. Using misaligned pointers can cause either a performance hit or a crashing application, depending on your platform.

However if you know that free memory and alignment are right, you can use placement new to construct your object there. However be aware that you also have to explicitly destruct it in that case. For example:

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

Upvotes: 4

Daniel
Daniel

Reputation: 31579

Use placement new for it:

#include <new>

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

Remember to delete it before you free the memory:

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

Do not create object on stack and memcpy it over, its not safe, what if the object has its address stored in a member or a member of a member?

Upvotes: 8

Related Questions