Return the copied object

In a function such as:

template<class Iterator>
A simple_return(Iterator it)
{
    return *it;
}

A a = simple_return(my_it); 

The compiler can easily perform RVO, so do the following:

template<class Iterator>
A simple_return(Iterator it)
{
    A tmp = *it;
    return tmp;
}

However, I saw that the second method is sometimes preferable to the first, for example, in implementations of the STL (gcc) algorithm, and I want to know if this affects the RVO in any way (like std::move(*it)or std::move(tmp)) or has any other reason, for example, in terms of conversions or anything else.

For example, reserver_iteratorand not:

reference operator*() const
{
     return *--Iterator(current);
}

uses:

reference operator*() const
{
     Iterator tmp = current;
     return *--tmp;
}

I ask because, to implement type overloads operator+, I use the template extensively:

friend A operator+(const A& a, const A& b)
{ return A(a) += b; }

instead:

friend A operator+(const A& a, const A& b)
{
    A tmp(a);
    return tmp += b;
}

This is not particularly readable, but makes it 3 lines longer (these two sentences on the same line will be ugly).

+4
1

- (NRVO) simple_return . . .

@cpplearner, STL, rvalues ​​(, Iterator ). .

+1

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


All Articles