C++ pointer and reference with new keyword when instantiating

后端 未结 2 1435
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 16:02

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

Book bk = new Book();

My professor recently did this

Book &         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-02 16:25

    This:

    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 there's one crucial difference; in the original code, you don't have a pointer which you can use to delete the dynamically-allocated object when you're done with it, so you've effectively created a memory leak.

    Of course, you could do this:

    delete &bk;
    

    but that's extremely non-idiomatic C++, and very likely to cause problems later.

    In summary, there's absolutely no good reason to write code like this, so don't do it. Either of the following is fine:

    Book bk;
    Book bk = Book();
    

提交回复
热议问题