C++ pointer and reference with new keyword when instantiating

后端 未结 2 1437
爱一瞬间的悲伤
爱一瞬间的悲伤 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:31

    I've found a situation that let me think about that syntax. Consider a smart pointer to a Base class and that has to hold a pointer to a derived class and you would like to access some non-virtual things of the derived class after the construction. 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 p( &d );
    

    Finally I still preferred the small arrows to the weird ampersands:

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

    But I think that in this a case is just a matter of taste, especially if you access a consistent number of methods.

    Other things that lead either to leaks or delete &d; are just bad, bad, bad.

提交回复
热议问题