Search code examples
c++new-operator

dynamically allocating a c++ object without using the new operator


(C++/Win32)

consider the following call:

Object obj = new Object(a,b);

other than allocating the virtual memory needed for an instance of an Object, what else is going on under the hood up there? does the compiler places an explicit call to the constructor of Object?

is there any way to initialize a c++ object dynamically without the use of the keyword new?


Solution

  • If you want to initialize an object in some given memory zone, consider the placement new (see this)

    BTW, the ordinary Object* n = new Object(123) expression is nearly equivalent to (see operator ::new)

     void* p = malloc(sizeof(Object));
     if (!p) throw std::bad_alloc; 
     Object* n = new (p) Object(123); // placement new at p, 
                                      // so invokes the constructor
    

    But the implementation could use some non-malloc compatible allocator, so don't mix new and free!