0

(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?

2 Answers2

4

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!

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

You can always use malloc instead of new, but don't forget to always couple it with free and not delete.

See also : What is the difference between new/delete and malloc/free?

Community
  • 1
  • 1
Oragon Efreet
  • 1,114
  • 1
  • 8
  • 25