返回值优化(RVO)不是一个错误吗?
我可能问了一个愚蠢的问题,但我在此处查看了 RVO 的维基百科页面,并且无法停止想知道这种行为是否错误。我在我的机器上尝试过,尽管有优化级别,但 RVO 已完全启动。如果构造函数中确实发生了大的事情怎么办?我知道不应该,但如果呢?我不明白为什么当构造函数中有副作用时 RVO 仍然会发生。
编辑:-fno-elide-constructors
似乎停止了 RVO。但问题仍然存在。
EDIT2:更严肃地说,有多少人知道这样的事情?它可能在标准中,但在我看来它仍然是一个非常丑陋的功能。至少编译器应该默认禁用它,并为了解这一点的人提供一个开关。 :)
编辑 3:我仍然坚持认为这真的很糟糕。 :)。我不认为我知道任何其他像这样直接违背语言语法的语言约束。其他一切都会引发编译器或链接器错误,对吧?
I maybe asking a dumb question, but I looked at the wikipedia page for RVO here and could not stop wondering if that behavior is wrong. I tried it in my machine and RVO is fully kicked in despite optimization level. What if there was actually something BIG happenning in a constructor? I know it shouldn't, but what if? I can't understand why RVO would still happen when there are side effects in the constructor.
EDIT: -fno-elide-constructors
seems to stop RVO. But the question remains.
EDIT2: On a more serious note, how many people know about something like this? It maybe in the standard, but it is still a really ugly feature as I see it. At least compilers should disable it by default and provide a switch for people who know about this. :)
EDIT 3: I still insist that this is really bad. :). I don't think I know of any other language constraint like this that goes directly against the syntax of language. Everything else throws either compiler or linker errors right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该标准规定,与程序的可观察状态有关的操作不得被优化掉,除了复制构造某些情况。您不能依赖复制构造函数来执行,即使它们具有您期望看到的副作用(例如,控制台输出)。
The standard mandates that operations with concern a program's observable state must not be optimized away, except for copy construction in certain circumstances. You must not rely on copy constructors to be executed, even if they have side effects you expect to see (e.g., console output).
正如其他答案中所述,编译器甚至可以优化不平凡的复制构造函数和赋值运算符。
As said in the other answers, the compiler is allowed optimize away even non trivial copy constructors and assignment operators.
定义“错误”。 C++ 语言明确允许这种优化,即使它是可观察到的。如果您的程序的行为取决于特定的实现,那么不幸的是您使用的不是 ISO C++,而是某种方言。
Define "wrong". The C++ language explicitly permits this kind of optimization even though it is observable. If the behavior of your program depends on a specific implementation, then unfortunately you are not using ISO C++, but some dialect.