最近我正在阅读APIboost::optional并且遇到了以下问题:
T const& operator *() const& ;
T& operator *() & ;
T&& operator *() && ;
Run Code Online (Sandbox Code Playgroud)
我还编写了自己的程序,将成员函数定义为const&,&和&&(请注意,我不是在谈论返回类型,而是在分号之前的说明符),它们似乎工作正常.
我知道声明一个成员函数const意味着什么,但任何人都可以解释它是什么意思来声明它const&,&和&&.
我对以下代码感到困惑,它(对我来说令人惊讶)编译:
class A {
int a=0;
};
A returnsA(void)
{
static A myA;
return myA;
}
void works(void)
{
A anotherA;
returnsA() = anotherA;
}
Run Code Online (Sandbox Code Playgroud)
我在标准或网络上找不到任何表明它不应该编译的内容。对我来说,这似乎很奇怪。
我猜想returnsA()返回一个对象( 的副本myA),因此我们对其调用默认的复制赋值运算符,anotherA将其复制分配给返回的对象,然后该对象超出范围并被销毁。
我期待的行为更像这样,但无法编译:
int returnsint(void)
{
static int i=0;
return i;
}
void doesntwork(void)
{
int anotherint=0;
returnsint() = anotherint;
}
Run Code Online (Sandbox Code Playgroud)
有人可以进一步启发我了解这种行为吗?