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
  • 3
    Define "dynamic". { Object obj{a,b}; } allocates an object as well, and destroys it, without any usage of new or delete. Commented Sep 24, 2013 at 15:44
  • And you really should explain why you ask! Notice that many standard containers are constructing objects.... Commented Sep 24, 2013 at 16:35

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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?

2 Comments

This does not invoke the constructor.
... or the destructor with free()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.