【发布时间】:2015-06-03 11:36:55
【问题描述】:
背景
以下代码块出现在 Scott Meyers 的名著"Effective C++" Item 3 中:
class TextBlock {
public:
...
const char& operator[](std::size_t position) const
{
... // do bounds checking
... // log access data
... // verify data integrity
return text[position];
}
char& operator[](std::size_t position)
{
... // do bounds checking
... // log access data
... // verify data integrity
return text[position];
}
...
private:
std::string text;
};
作者指出,在上述实现中,const 和非const 重载的内容本质上是相同的。为了避免代码重复,可以这样简化:
class TextBlock {
public:
...
const char& operator[](std::size_t position) const // the same as before
{
...
...
...
return text[position];
}
char& operator[](std::size_t position) // now just calls const op[]
{
return // cast away const on
const_cast<char&>( // op[]'s return type;
static_cast<const TextBlock&>(*this) // add const to *this's type;
[position] // call const version of op[]
);
}
...
private:
std::string text;
};
问题
我的问题是:
-
我们什么时候需要一个重载
const T&和另一个T&&? (这里,T可能是模板参数或类类型,所以T&&可能表示也可能不表示通用引用)我可以看到,在标准库中,许多类都提供了这两种重载。例如std::pair和std::tuple的构造函数,有大量的重载。 (好的,我知道函数中,一个是拷贝构造函数,一个是移动构造函数。) -
是否有类似的技巧来共享
const T&和T&&重载的实现?我的意思是,如果const T&&重载返回一个复制构造的对象,而T&&重载返回的是移动构造的东西,那么在共享实现之后,这个属性必须仍然成立。 (就像上面的技巧:const返回const和非const返回非const,实现共享前后都一样)
谢谢!
说明
我所指的两个重载应该如下所示:
Gadget f(Widget const& w);
Gadget f(Widget&& w);
与右值引用返回无关,即:
Widget&& g(/* ... */);
(顺便说一下,my previous post 已经解决了这个问题)
在上面的f() 中,如果Gadget 既可复制构造又可移动构造,则无法(除了阅读实现)来判断返回值是复制构造还是移动构造。与返回值优化(RVO)/命名返回值优化(NRVO)无关。 (见my previous post)
参考文献
【问题讨论】:
标签: c++ c++11 rvalue-reference rvalue pass-by-rvalue-reference