What is preferred way of passing pointer/reference to existing object in a constructor?

后端 未结 4 1580
野趣味
野趣味 2021-02-19 00:52

I\'ll start from example. There is a nice \"tokenizer\" class in boost. It take a string to be tokenized as a parameter in a constructor:

std::string string_to_t         


        
4条回答
  •  独厮守ぢ
    2021-02-19 01:40

    As others said, the boost::tokenizer example is the result of either a bug in the tokenizer or a warning missing from the documentation.

    To generally answer the question, I found the following priority list useful. If you can't choose an option for some reason, you go to the next item.

    1. Pass by value (copyable at an acceptable cost and don't need to change original object)
    2. Pass by const reference (don't need to change original object)
    3. Pass by reference (need to change original object)
    4. Pass by shared_ptr (the lifetime of the object is managed by something else, this also clearly shows the intention to keep the reference)
    5. Pass by raw pointer (you got an address to cast to, or you can't use a smart pointer for some reason)

    Also, if your reasoning to choose the next item from the list is "performance", then sit down and measure the difference. In my experience, most people (especially with Java or C# backgrounds) tend to over-estimate the cost of passing an object by value (and under-estimate the cost of dereferencing). Passing by value is the safest option (it will not cause any surprises outside the object or function, not even in another thread), don't give up that huge advantage easily.

提交回复
热议问题