Reputation: 2347
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.
Upvotes: 20
Views: 46012
Reputation: 153899
Any of the usual ways: as a local or static variable, or as
a temporary. In general, the only times you use new
in C++ is
when the object has identity and a lifetime which doesn't
correspond to a scope, or when it is polymorphic. (There are
exceptions, of course, but not many.) If the object can be
copied, it's usually preferable to use local instances, copying
those as needed. (Just like you would for int
, in fact.)
Upvotes: 2
Reputation: 361282
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:
Upvotes: 31
Reputation: 51
Using malloc will give you the same result as new, just without calling the constructor.
Upvotes: 0