unique_ptr and polymorphism

后端 未结 4 2040
深忆病人
深忆病人 2021-02-07 10:59

I have some code that currently uses raw pointers, and I want to change to smart pointers. This helps cleanup the code in various ways. Anyway, I have factory methods that retur

4条回答
  •  悲哀的现实
    2021-02-07 11:29

    Well, if your functions operate on the (pointed to) object itself and don't need its address, neither take any ownership, and, as I guess, always need a valid object (fail when passed a nullptr), why do they take pointers at all?

    Do it properly and make them take references:

    void Push(const Object& object) { ... }
    

    Then the calling code looks exactly the same for raw and smart pointers:

    auto number = NewNumber(5);
    Push(*number);
    

    EDIT: But of course no matter if using references or pointers, don't make Push take a std::unique_ptr if it doesn't take ownership of the passed object (which would make it steal the ownership from the passed pointer). Or in general don't use owning pointers when the pointed to object is not to be owned, std::shared_ptr isn't anything different in this regard and is as worse a choice as a std::unique_ptr for Push's parameter if there is no ownership to be taken by Push.

提交回复
热议问题