When should you return a reference to a object from a class method

后端 未结 7 1742
旧时难觅i
旧时难觅i 2021-02-14 01:14

What is the best practice for returning references from class methods. Is it the case that basic types you want to return without a reference whereas class objects you want to r

7条回答
  •  离开以前
    2021-02-14 01:50

    A reference is a pointer in disguise (so it's 4 bytes on 32 bit machines, and 8 bytes on 64 bit machines). So the rule of thumb is: if copying the object is more expensive than returning a pointer, use a pointer (or reference, since that's the same thing).

    Which types are more expensive to copy depends on the architecture, compiler, the type itself etc. In some cases copying an object that's 16 bytes can be faster than returning a pointer to it (for example, if an object maps to SSE register, or similar situation).

    Now, of course, returning a reference to a local variable does not make sense. Because the local variable will be gone after the function exits. So usually you'd return references/pointers to member variables, or global/static variables, or dynamically allocated objects.

    There are situations where you don't want to return pointer/reference to an object, even if copying the object is expensive. Mostly when you don't want to tie the calling code into the lifetime of the original object.

提交回复
热议问题