C ++ pointer and link with new keyword when instantiating

When I want to instantiate a class in C ++, I usually go this way

Book bk = new Book(); 

Recently, my professor did this

 Book &bk = *new Book(); 

He only told me that he would use the link to be able to use a period (for example, bk.getTitle ();) instead of an arrow (for example, bk-> getTitle ();). I understand this part of the code, but what happens when you use the * operator in conjunction with the new?

Thanks in advance

full example code can be found here is arraystack in main function

+7
source share
2 answers

It:

 Book &bk = *new Book(); 

pretty much equivalent to this:

 Book *p = new Book(); // Pointer to new book Book &bk = *p; // Reference to that book 

But there is one important difference; in the source code you don’t have a pointer that you can use to delete object with dynamic allocation when you are done with it, so you effectively created a memory leak.

Of course you can do this:

 delete &bk; 

but this is extremely non-idiomatic C ++ and is likely to cause problems later.

Thus, there is absolutely no reason to write such code, so do not do this . Any of the following is fine:

 Book bk; Book bk = Book(); 
+15
source

I found a situation that allowed me to think about this syntax. Consider a smart pointer to a Base class that must contain a pointer to a derived class, and you want to access some non-virtual things of the derived class after building. In this case, something like this is legal and may not be so bad:

 Derived & d = * new Derived(); d.d_method( ..whatever.. ); d.d_member = ..whatever..; ... std::unique_ptr<Base> p( &d ); 

Finally, I still preferred small arrows for weird ampersands:

 Derived d = new Derived(); d->d_method( ..whatever.. ); d->d_member = ..whatever..; ... std::unique_ptr<Base> p( d ); 

But I think that in this case it’s just a matter of taste, especially if you get access to a consistent number of methods.

Other things that cause leaks or delete &d; just bad, bad, bad.

0
source

All Articles