Return fstream

I have this function:

fstream open_user_file() const
{
    ...
}

but my compiler complains that fstreamcopy-constructor is implicitly deleted. Given that the compiler performs RVO, why is the copy constructor selected instead of the move constructor?

Otherwise, what is the best way to do this?

+4
source share
2 answers

The accepted answer is currently invalid.

When returning a local variable with automatic storage of the same type as the declared return type of the function, a two-phase process occurs:

fstream open_user_file() const
{
    fstream f;

    /*...*/

    return f;
}
  • Choosing a constructor for the copy is first performed as if the object was designated rvalue.

  • , rvalue (, cv), , lvalue.

, f , (, , ) f. Else, f , (, , ) f. f .

, :

return std::move(f);

, . fstream :

return f;

. f , :

return std::move(f);

. , RVO.

gcc 4.8 ( ). . ++ 98, ++ 03 gcc 4.8 . ++ 11 .

+8

return, . .

fstream open_user_file() const
{
    fstream f;

    /*...*/

    return std::move(f);
}

/ , , / / .

...

, :

, , object - , lvalue, ,, rvalue. rvalue (, cv-), , . [. , . , elision , , .

+3

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


All Articles