Malloc and constructors
Unlike new and delete operators mal开发者_JAVA技巧loc does not call the constructor when an object is created. In that case how must we create an object so that the constructor will also be called.
Er...use new
? That's kind of the point. You can also call the constructor explicitly, but there's little reason to do it that way
Using new/delete normally:
A* a = new A();
delete a;
Calling the constructor/destructor explicitly ("placement new"):
A* a = (A*)malloc(sizeof(A));
new (a) A();
a->~A();
free(a);
You can use "placement new" syntax to do that if you really, really need to:
MyClassName* foo = new(pointer) MyClassName();
where pointer
is a pointer to an allocated memory location large enough to hold an instance of your object.
Prefer new
.
But if for some reason you have raw memory, you can construct it with "placement new":
new (ptr) TYPE(args);
And since you won't be using delete, you'll need to call the destructor directly:
ptr->~TYPE();
You mis-understand what malloc does. malloc does not create objects, it allocates memory. As it does not create objects there is no object for it to call a constructor to create.
If you need to dynamically create an object in C++ you need to use some form of new.
Use placement new
. The advice is handy:
ADVICE: Don't use this "placement new" syntax unless you have to. Use it only when you really care that an object is placed at a particular location in memory. For example, when your hardware has a memory-mapped I/O timer device, and you want to place a Clock object at that memory location.
Take a look at placement new operator, which constructs an object on a pre-allocated buffer.
class A
{
public:
A() { printf("Constructor of A"); }
};
int main()
{
A* pA = (A*) malloc(sizeof(A)); // Construtor is not going to be called.
__asm { MOV EAX, pA} // Makes pA as "this" pointer in intel based s/m.
A(); // Calling constructor explicitly.
return 0;
}
精彩评论