如何防止赋值运算符左侧出现临时性 [英] How to prevent a temporary on the left hand side of the assignment operator
问题描述
如果我为类型定义operator+
,则采用通常的方式
If I define operator+
for a type, in the usual fashion
struct S {};
S operator+(S const &, S const &) {
return {};
}
S
的用户可以编写类似
S s{};
s + s = S{}; // huh
据我所知,operator+
返回类型为S
的临时对象,然后将其分配给该对象.然后该对象在语句的末尾死亡,因为它没有名称,因此该语句实际上是无操作的.
From what I can tell, operator+
returns a temporary object of type S
, which is then assigned to. The object then dies at the end of the statement, because there's no name for it, and so the statement is effectively a no-op.
我没有看到类似的代码用处,因此我想使它成为编译错误.有没有办法做到这一点?即使是警告也总比没有好.
I don't see any use for code like that, so I would like to make that a compile error. Is there a way to do that? Even a warning would be better than nothing.
推荐答案
Just found what I need here. Apparently I can make the assignment operator only bind to lvalues.
struct S {
S& operator=(S const&) & // only binds to lvalues
{
return *this;
}
};
现在我完全得到了我想要的错误.
Now I get exactly the error I want.
这篇关于如何防止赋值运算符左侧出现临时性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!