(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
?
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
!
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.