Just a simple question. As the title suggests, I've only used the "new" operator to create new instances of a class, so I was wondering what the other method was and how to correctly use it.
In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object.
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
You can also have automatic instances of your class, that doesn't use new
, as:
class A{};
//automatic
A a;
//using new
A *pA = new A();
//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();
//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();
The last two are using placement-new which is slightly different from just new. placement-new is used to construct the object by calling the constructor. In the third example, malloc
only allocates the memory, it doesn't call the constructor, that is why placement-new is used to call the constructor to construct the object.
Also note how to delete the memory.
//when pA is created using new
delete pA;
//when pA is allocated memory using malloc, and constructed using placement-new
pA->~A(); //call the destructor first
free(pA); //then free the memory
//when pA constructed using placement-new, and no malloc or new!
pA->~A(); //just call the destructor, that's it!
To know what is placement-new, read these FAQs:
You can just declare a normal variable:
YourClass foo;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With