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

前端 未结 7 1750
挽巷
挽巷 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:50

    tl;dr: Do not use unique_ptr's like that.

    I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.

    1. Only take unique_ptr constructor parameters if you have publicly-exposed unique_ptr members.

    unique_ptrs wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner as suggested in the Core Guidelines.

    Only if the purpose of your class is to hold unique_ptr's, and have others use those unique_ptr's as such - only then is it reasonable for your constructor or methods to take them.

    1. Don't expose the fact that you use unique_ptrs internally

    Using unique_ptr for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.

提交回复
热议问题