" Effective C++ "第3项说"尽可能使用const",它给出了一个例子:
const Rational operator*(const Rational& lhs,
const Rational& rhs);
Run Code Online (Sandbox Code Playgroud)
防止客户端犯下这样的暴行:
Rational a, b, c;
...
(a * b) = c; // invoke operator= on the result of a*b!
Run Code Online (Sandbox Code Playgroud)
但是,函数的非参考返回值是否已经是一个rvalue?那么为什么还要这么做呢?
我有习惯(?!?!?)将所有内容作为"const"值返回.像这样...
struct s;
s const make_s();
s const &s0 = make_s();
s const s1 = make_s();
Run Code Online (Sandbox Code Playgroud)
使用移动操作和r值引用以及以下功能......
void take_s(s &&s0);
void take_s(s const &&s0); // Doesn't make sense
Run Code Online (Sandbox Code Playgroud)
我不能再写了......
take_s(make_s());
Run Code Online (Sandbox Code Playgroud)
我开始使用返回const值的约定的主要原因是为了防止有人编写这样的代码......
make_s().mutating_member_function();
Run Code Online (Sandbox Code Playgroud)
用例如下......
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 > …Run Code Online (Sandbox Code Playgroud)