简体   繁体   English

如何防止赋值运算符左侧的临时

[英]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...当然,这还有其他一些后果,可能会或可能不会有不良副作用,这可能会或可能不会造成问题,但这将是一个新问题,在这里......

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.现在我得到了我想要的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在左右两侧创建运算符*(double)以进行相乘? - How to create operator*(double) for multiplying on both the left and right hand side? 当对象位于赋值的右侧时,重载赋值运算符 - Overloading assignment operator when the object is on the right-hand side of the assignment 函数是否可以位于赋值运算符的左侧? - Can a function ever be on the left side of an assignment operator? 赋值运算符(字符串)右侧的类型是什么? - What is the type of the right hand side of the assignment operator (string)? 下标是否在赋值运算符的右侧之前计算 - does subscript evaluate before the right hand side of assignment operator 在分配的右侧使用减量运算符是否有效的C ++? - Is using a predecrement operator on the right hand side of an assignment valid C++? 移动分配时左侧 std::vector 资源会发生什么变化? - What happens to the left hand side std::vector resources on move assignment? 在示波器分辨率运算符的左侧使用“&”号? - use of ampersand on left hand side of scope resolution operator? 如何从屏幕右侧而不是 C 中通常的左侧按 output 进行打印? - How to print by output from the right hand side of the screen instead of the usual left hand side in C? 如何防止使用继承的运算符 [] 赋值? - How to prevent value assignment with inherited operator[]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM