How do I pass a unique_ptr argument to a constructor or a function?

前端 未结 7 1749
挽巷
挽巷 2020-11-22 06:16

I\'m new to move semantics in C++11 and I don\'t know very well how to handle unique_ptr parameters in constructors or functions. Consider this class referenc

7条回答
  •  离开以前
    2020-11-22 06:56

    To the top voted answer. I prefer passing by rvalue reference.

    I understand what's the problem about passing by rvalue reference may cause. But let's divide this problem to two sides:

    • for caller:

    I must write code Base newBase(std::move()) or Base newBase().

    • for callee:

    Library author should guarantee it will actually move the unique_ptr to initialize member if it want own the ownership.

    That's all.

    If you pass by rvalue reference, it will only invoke one "move" instruction, but if pass by value, it's two.

    Yep, if library author is not expert about this, he may not move unique_ptr to initialize member, but it's the problem of author, not you. Whatever it pass by value or rvalue reference, your code is same!

    If you are writing a library, now you know you should guarantee it, so just do it, passing by rvalue reference is a better choice than value. Client who use you library will just write same code.

    Now, for your question. How do I pass a unique_ptr argument to a constructor or a function?

    You know what's the best choice.

    http://scottmeyers.blogspot.com/2014/07/should-move-only-types-ever-be-passed.html

提交回复
热议问题