[英]How to prevent a temporary on the left hand side of the assignment operator
If I define operator+
for a type, in the usual fashion如果我以通常的方式为类型定义
operator+
struct S {};
S operator+(S const &, S const &) {
return {};
}
users of S
can write code like S
的用户可以编写如下代码
S s{};
s + s = S{}; // huh
From what I can tell, operator+
returns a temporary object of type S
, which is then assigned to.据我所知,
operator+
返回一个S
类型的临时 object ,然后分配给它。 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. object 然后在语句结束时死掉,因为它没有名字,所以该语句实际上是一个空操作。
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.
即使是警告也比没有好。
One simple way to prevent this from happening is to return a constant object:防止这种情况发生的一种简单方法是返回一个常量 object:
const S operator+(S const &, S const &) {
return {};
}
That will now result in a compilation error, in this situation, but在这种情况下,现在会导致编译错误,但是
s= s + s;
will still work just fine.仍然可以正常工作。
This, of course, has a few other ramifications, and may or may not have undesirable side-effects, which may or may not pose an issue, but that would be a new question, here...当然,这还有其他一些后果,可能会或可能不会有不良副作用,这可能会或可能不会造成问题,但这将是一个新问题,在这里......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.