[ACCEPTED]-C++ pointer and reference with new keyword when instantiating-reference
Book &bk = *new Book();
is pretty much equivalent to this:
Book *p = new Book(); // Pointer to new book Book &bk = *p; // Reference to that book
But 10 there's one crucial difference; in the original 9 code, you don't have a pointer which you 8 can use to
delete the dynamically-allocated object 7 when you're done with it, so you've effectively 6 created a memory leak.
Of course, you could 5 do this:
but that's extremely non-idiomatic C++, and 4 very likely to cause problems later.
In summary, there's 3 absolutely no good reason to write code 2 like this, so don't do it. Either of the following 1 is fine:
Book bk; Book bk = Book();
I've found a situation that let me think 12 about that syntax. Consider a smart pointer 11 to a
Base class and that has to hold a pointer 10 to a derived class and you would like to 9 access some non-virtual things of the derived 8 class after the construction. In this case 7 something like this is legal and may not 6 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 the 5 small arrows to the weird ampersands:
Derived d = new Derived(); d->d_method( ..whatever.. ); d->d_member = ..whatever..; ... std::unique_ptr<Base> p( d );
But 4 I think that in this a case is just a matter 3 of taste, especially if you access a consistent 2 number of methods.
Other things that lead 1 either to leaks or
delete &d; are just bad, bad, bad.
More Related questions