I have the habit (?!?!?) of returning everything as a "const" value. Like this...
struct s;
s const make_s();
s const &s0 = make_s();
s const s1 = make_s();
With move operations and r-value references and the following functions...
void take_s(s &&s0);
void take_s(s const &&s0); // Doesn't make sense
I can no longer write...
take_s(make_s());
The main reason I started using the convention of returning const values is to prevent someone from writing code like this...
make_s().mutating_member_function();
The use case is the following...
struct c_str_proxy {
std::string m_s;
c_str_proxy(std::string &&s) : m_s(std::move(s)) {
}
};
c_str_proxy c_str(std::string &&s) {
return c_str_proxy(s);
}
char const * const c_str(std::string const &s) {
return s.c_str();
}
std::vector < std::string > const &v = make_v();
std::puts(c_str(boost::join(v, ", ")));
std::string const my_join(std::vector < std::string > const &v, char const *sep);
// THE FOLLOWING WORKS, BUT I THINK THAT IS ACCIDENTAL
// IT CALLS
//
// c_str(std::string const &);
//
// BUT I THINK THE TEMPORARY RETURNED BY
//
// my_join(v, "; ")
//
// IS NO LONGER ALIVE BY THE TIME WE ARE INSIDE
//
// std::puts
//
// AS WE ARE TAKING THE "c_str()" OF A TEMPORARY "std::string"
//
std::puts(c_str(my_join(v, "; ")));
Looks as if "returning const value" and r-value references don't mix in this particular use case. Is that right?
**Edit 0: Extra question...**
The object is temporary anyway. Why should "const" prevent moving? Why can't we move "const" temporaries?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…