std::auto_ptr to std::unique_ptr

后端 未结 4 1429
無奈伤痛
無奈伤痛 2020-11-28 00:46

With the new standard coming (and parts already available in some compilers), the new type std::unique_ptr is supposed to be a replacement for std::auto_p

4条回答
  •  盖世英雄少女心
    2020-11-28 01:39

    std::auto_ptr and std::unique_ptr are incompatible in someways and a drop in replacement in others. So, no find/replace isn't good enough. However, after a find/replace working through the compile errors should fix everything except weird corner cases. Most of the compile errors will require adding a std::move.

    • Function scope variable:
      100% compatible, as long as you don't pass it by value to another function.
    • Return type:
      not 100% compatible but 99% compatible doesn't seem wrong.
    • Function parameter by value:
      100% compatible with one caveat, unique_ptrs must be passed through a std::move call. This one is simple as the compiler will complain if you don't get it right.
    • Function parameter by reference:
      100% compatible.
    • Class member variable:
      This one is tricky. std::auto_ptrs copy semantics are evil. If the class disallows copying then std::unique_ptr is a drop in replacement. However, if you tried to give the class reasonable copy semantics, you'll need to change the std::auto_ptr handling code. This is simple as the compiler will complain if you don't get it right. If you allowed copying of a class with a std::auto_ptr member without any special code, then shame on you and good luck.

    In summary, std::unique_ptr is an unbroken std::auto_ptr. It disallows at compile time behaviors that were often errors when using a std::auto_ptr. So if you used std::auto_ptr with the care it needed, switching to std::unique_ptr should be simple. If you relied on std::auto_ptr's odd behavior, then you need to refactor your code anyway.

提交回复
热议问题