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

后端 未结 4 1594
野趣味
野趣味 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:24

    If some function (such as a constructor) takes an argument as reference-to-const then it should either

    • Document clearly that the lifetime of the referenced object must satisfy certain requirements (as in "Is not destroyed before this and that happens")

    or

    • Create copies internally if it needs to make use of the given object at a later point.

    In this particular case (the boost::tokenizer class) I'd assume that the latter isn't done for performance reasons and/or to make the class usable with container types which aren't even copyable in the first place. For this reason, I'd consider this a documentation bug.

提交回复
热议问题