Const <type> & foo () compared to <type> foo ()

In a class without a template , is there any reason to prefer the function of return signatures in the form of const <type>& foo();versus <type> foo();? Where <type>is the inner type. And if <type>- a class / struct object?

Also wondered if const: const <type>& foo() const;to value matters<type> foo() const;

eg. in a class without a template, a function without a template:

const int& foo() const { return member_variable_; }

Compared to

int foo() const { return member_variable_; }
+3
source share
5 answers

For primitive types, just return by value. There is no reason to return a primitive through a const reference.

For non-primitive types, this depends.

, . , .

, .

const , . , .. . , , , :

const X& x = y->foo();
delete y;
// use x, oops!

, , (, , get(), ). , , , (: memcpy ).

: const , /, , .

, , (, ):

void foo(X& return_val) { return_val = member_variable_; }

void foo(X* return_val) {
    assert(return_val != 0);
    *return_val = member_variable_;
}
+3

, - . , - :

struct A {
   X x;
    ...
   X f1() { return x; }
   const X & f2() { return x; }
};

.

0

, .

, , :

<type>& foo()  { ... }

, , const , :

const <type>& foo() { ... }

, , ( const), :

<type>& foo() const { ... }

, , const , ( const), :

const <type>& foo() const { ... }

: , ...

0
const <type>& foo();

, , foo() , , , const , / . const , , , , , foo(), const. , , , , const. api usecase.

<type> foo();

<type>. , . , , , <type> - , int.

0

, const refs , ; . ASM, , , return , , ; .

If it is a class or structure, it depends on the lifetime of the value; if it is local to the function, then it cannot be returned; otherwise, if it is a member of the class, I prefer the type const & since it can offer better performance, avoiding copy constructors. (opinions differ, since it is considered safer in value). It also eliminates the need to create copy instances or use the potentially evil ones by default, which is nice.

0
source

Source: https://habr.com/ru/post/1728099/


All Articles