Returning a const reference to an object instead of a copy

前端 未结 12 559
天命终不由人
天命终不由人 2020-11-29 16:40

Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:

class foo
{
private:
    std::st         


        
12条回答
  •  有刺的猬
    2020-11-29 17:37

    It is conceivable that you could break something if the caller really wanted a copy, because they were about to alter the original and wanted to preserve a copy of it. However it is far more likely that it should, indeed, just be returning a const reference.

    The easiest thing to do is try it and then test it to see if it still works, provided that you have some sort of test you can run. If not, I'd focus on writing the test first, before continuing with refactoring.

提交回复
热议问题