c++ - 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
struct S {};
S operator+(S const &, S const &) {
return {};
}
users of S
can write code like
S s{};
s + s = S{}; // huh
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.
解决方案
One simple way to prevent this from happening is to return a constant 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...
推荐阅读
- python - 在 Python 中用一行代码编写阶乘函数
- .net - 如何说服 VS Code 引用一个包的最新版本?
- header - 如何使用 H264 编解码器为 MP4 文件编写带有 libavcodec 的 avc1 atom
- bash - 读写两个进程的同一个文件是否需要lockfile
- python - Python - 无效的语法错误
- spring - Spring 5 Webclient 的默认超时
- django - Apache2 WSGI Django - 目录访问
- vue.js - '[Object object]' 在 Vue.js 数据列表中显示而不是标签
- java - 将 GUI 链接到主类
- elasticsearch - NEST 的 PolygonShape 的错误