我有将所有内容作为“const”值返回的习惯(?!?!?)。像这样...
struct s;
s const make_s();
s const &s0 = make_s();
s const s1 = make_s();
使用移动操作和右值引用以及以下功能...
void take_s(s &&s0);
void take_s(s const &&s0); // Doesn't make sense
我已经写不下去了……
take_s(make_s());
我开始使用返回 const 值的约定的主要原因是为了防止有人编写这样的代码......
make_s().mutating_member_function();
用例如下...
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, "; ")));
看起来好像“返回 const 值”和 r 值引用不会在这个特定用例中混合使用。那正确吗?
**Edit 0: Extra question...**
无论如何,该对象是临时的。为什么“const”应该阻止移动?为什么我们不能移动“const”临时对象?