Returning a const reference to an object instead of a copy

前端 未结 12 593
天命终不由人
天命终不由人 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:31

    Some implementations of std::string share memory with copy-on-write semantics, so return-by-value can be almost as efficient as return-by-reference and you don't have to worry about the lifetime issues (the runtime does it for you).

    If you're worried about performance, then benchmark it (<= can't stress that enough) !!! Try both approaches and measure the gain (or lack thereof). If one is better and you really care, then use it. If not, then prefer by-value for the protection it offers agains lifetime issues mentioned by other people.

    You know what they say about making assumptions...

提交回复
热议问题