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

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

    A lot of time it will depend on context, for example if it's a functor which will be called in a for_each or similar, then you will often store a reference or a pointer within your functor to an object you expect will have a lifetime beyond your functor.

    If it is a general use class then you have to consider how people are going to use it.

    If you are writing a tokenizer, you need to consider that copying what you are tokenizing over might be expensive, however you also need to consider that if you are writing a boost library you are writing it for the general public who will use it in a multi-purpose way.

    Storing a const char * would be better than a std::string const& here. If the user has a std::string then the const char * will remain valid as long as they don't modify their string, and they probably won't. If they have a const char * or something that holds an array of chars and passes it in, it will copy it anyway to create the std::string const & and you are in great danger of the fact that it won't live past your constructor.

    Of course, with a const char * you can't use all the lovely std::basic_string functions in your implementation.

    There is an option to take, as parameter, a std::string& (not const reference) which should guarantee (with a compliant compiler) that nobody will pass in a temporary, but you will be able to document that you don't actually change it, and the rationale behind your seemingly not const-correct code. Note, I have used this trick once in my code too. And you can happily use string's find functions. (As well as, if you wish, taking basic_string rather than string so you can tokenize wide character strings too).

提交回复
热议问题