PENGUINLIONG
PENGUINLIONG

Reputation: 573

What does (new Class())->Function(); mean?

I have seen this form in the blog of one of the employees of MS. But what does it mean? I'm confused because he didn't delete after using the new operator. Is that completely legal? Or it can only be used in Visual C++?

Source code from his blog:

(new RegForm())->ShowMaximized();
GetApplication()->Run();

Upvotes: 2

Views: 79

Answers (2)

Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

It is exactly same as

RegForm* pForm = new RegForm();
pForm->ShowMaximized();

There is no tight and strict rule that saying delete all news before end the programe. programmer should know what he do and avoid memory leaks (specially in repetitive task). by the way all the memory will be clean when the application exit.

Upvotes: 0

M.M
M.M

Reputation: 141554

Firstly it's legal to new things and not delete them. It may cause a memory leak but that is permitted in C++.

In this specific piece of code, new generates a pointer to an object. You can use -> on a pointer to call a member function of the object, so this creates the RegForm and then calls ShowMaximized on it.

We can't tell from this code whether or not there is a memory leak. However RegForm might be using a sort of self-registration pattern. For example its constructor might contain:

GlobalListOfObjectsToDeleteLater.push_back(this);

and when the application shuts down , another piece of code will go through the list deleting everything.

In fact, it seems likely that RegForm registers itself with some other part of the GUI , it would have to do that in order to be able to Show itself.

Upvotes: 4

Related Questions