【发布时间】:2011-08-21 14:18:31
【问题描述】:
我有将所有内容作为“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”临时对象?
【问题讨论】:
-
我并没有真正看到首先返回 const 值的理由。为什么要关心防止人们在返回的对象上调用变异成员函数?
-
可以在 Meyers, "More Effective c++", 1996, Item 6 中找到一个 const value return idiom 的例子。Meyers 推荐
const T operator++(int)作为 postfix++ 的签名。
标签: c++ c++11 constants return-value move-semantics