unique_ptr and polymorphism

后端 未结 4 2032
深忆病人
深忆病人 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:24

    Initially I decided to simply change the definition of Push to use unique_ptrs too, but this generates compile errors when trying to use derived types.

    You likely did not correctly deal with uniqueness.

    void push(std::unique_ptr);
    int main() {
        std::unique_ptr i;
        push(i); // Illegal: tries to copy i.
    }
    

    If this compiled, it would trivially break the invariant of unique_ptr, that only one unique_ptr owns an object, because both i and the local argument in push would own that int, so it is illegal. unique_ptr is move only, it's not copyable. It has nothing to do with derived to base conversion, which unique_ptr handles completely correctly.

    If push owns the object, then use std::move to move it there. If it doesn't, then use a raw pointer or reference, because that's what you use for a non-owning alias.

提交回复
热议问题