Should accessors return values or constant references?

后端 未结 8 1262
谎友^
谎友^ 2020-12-05 08:17

Suppose I have a class Foo with a std::string member str. What should get_str return?

std::string Foo::ge         


        
相关标签:
8条回答
  • 2020-12-05 08:52

    In general (unless there's a proven performance issue) I would return by value.

    First of all there's a semantic difference, if your property changes do you want your clients to be updated of the change or get the value at the moment of calling the function?

    There's the obvious correctness issue, if you return by reference the entity calling the function may hold on to the reference and may use it after your object was destructed (which is not so good).

    Another problem is with multiple threaded code, if one thread reads from the const reference while you're updating the variable your in for lots of trouble.

    In any case I think the most common use case is when the caller of the function stores the value in a variable.

    string val = obj->get_str();
    // use val now
    

    If this is true (as opposed to cout << obj->get_str() where there is no variable) you always have to construct a new string for val even if you return by reference and since compilers can perform RVO the by-value version will not under-perform the by-const-ref variant.


    In conclusion: if you know it's a performance issue and you are sure that the return value will not be stored for longer than your object will exist and you don't expect to be used from different threads, then it's OK to return by const reference.

    0 讨论(0)
  • 2020-12-05 08:53

    Generally you should return PODs by value (e.g, int, short, char, long etc,) and a const reference for more complex types:

    int getData() const;
    short getMoreData() const;
    const std::string& getName() const;
    const ComplexObject& getComplexData() const;
    
    0 讨论(0)
提交回复
热议问题