Int foo (type & bar); is this a bad practice?

Well, here we are. Another suggested practice that my C ++ book expresses its opinion on. It says that the return value function (non-void) should not accept reference types as a parameter. "Thus, basically, if you were to implement such a function:

int read_file(int& into){
   ...
}

and used the integer return value as some kind of error indicator (ignoring the fact that we have exceptions), then this function will be poorly written, and it should look like

void read_file(int& into, int& error){

}

Now for me the first of them is much more understandable and pleasant to use. If you want to ignore the meaning of the error, you do it with ease. But this book offers later. Note that this book does not say that function return values ​​are bad. This rather suggests that you should either return a value or use only links.

What do you think about this? Is my book full of crap? (again)

+3
source share
5 answers

The advice is stupid. The direct return value is much smaller and easier to enter.

Direct Return:

if (read_file(...)) {
    ... handle problem ...
}

Indirect Return:

int status;

read_file(..., status);
if (status) {
    ... handle problem ...
}

: , const. , . , const, . , & , "- ".

+10

, , .

+5

. std::pair, struct ( TR1) .

+3

" , "

- :

int read_file(const int& into){ ... }

, const , , , . int, .


: , , , , , , "" - , ..

+1
//somewhere deep in the code space
a = func(i); //i is modified inside func() or not?    
j = i; //what is this for? depends on the answer to the first question

If the code was written in relation to the rule suggested in the book, you can be sure that the “i” does not change just by looking at the call site, so the code tells you more than otherwise

In any case, I would prefer to return the tuple without changing the link

0
source

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


All Articles