Re: std::pair, segmentation fault, why?
On 19 Sep., 08:07, Kai Wen wrote:
=========================
==========================
==========
#include <iostream>
#include <set>
#include <boost/tuple/tuple.hpp>
typedef boost::tuple<std::set<int>, int> first_type;
typedef boost::tuple<std::set<int>, std::pair<int, int>> second_type;
first_type&& foo1()
{
std::set<int> s{1, 2, 3};
return std::move(boost::make_tuple(s, 22));
}
You're returning a dangling reference (a reference to a function local
object that ceases to exist). This is what you should have written:
#include <utility> // provides std::move
first_type foo1()
{
using namespace std;
set<int> s{1, 2, 3};
return boost::make_tuple(move(s), 22);
}
Avoid writing functions which return rvalue references. There are a
couple of exceptions where this is okay (std::move and std::forward
are special-purpose functions where it actually makes sense). In
almost all other cases this is probably wrong to begin with. Rvalue
references are still references which could get invalid just as well
as lvalue references.
Also, you should never ever (!) write
return std::move(function_local_or_temporary_object);
The std::move here is redundant as the compiler will automatically
consider move constructing the return value from a "pure" function
local object. In fact, using std::move is likely to *inhibit* further
optimizations such as NRVO which would be even better than a move
construction of the return value.
Cheers!
SG