普通视图

发现新文章,点击刷新页面。
昨天以前首页

C++ programmer's guide to undefined behavior: part 2 of 11

作者 Andrey Karpov
2024年6月30日 19:31

Your attention is invited to the second part of an e-book on undefined behavior. This is not a textbook, as it's intended for those who are already familiar with C++ programming. It's a kind of C++ programmer's guide to undefined behavior and to its most secret and exotic corners. The book was written by Dmitry Sviridkin and edited by Andrey Karpov.

C++ programmer's guide to undefined behavior: part 2 of 11

by Dmitry Sviridkin

From the article:

The compiler can be guided by the following logic: If the h value is positive—regardless of the c character—the h*27752 + c value will be positive: the c value is small, and there is no overflow. At the first iteration, h is positive, we sum up positive numbers. There are no overflows in a correct program, so at each iteration, the value will be positive. The result will be positive; we no need any check.

More on Harmful Overuse of std::move -- Raymond Chen

作者 Blog Staff
2024年6月30日 05:46

RaymondChen_5in-150x150.jpgIn recent discussions around the use of std::move in C++, questions have arisen regarding its potential overuse and the compiler's treatment of its return values. Addressing concerns raised by developers like Jonathan Duncan, this article delves into the nuances of std::move, examining whether its current implementation aligns with compiler optimizations and proposing potential enhancements for more efficient code generation.

More on harmful overuse of std::move

by Raymond Chen

From the article:

Some time ago, I wrote about harmful overuse of std::move. Jonathan Duncan asked,

Is there some side-effect or other reason I can’t see return std::move(name); case isn’t possible to elide? Or is this just a case of the standards missing an opportunity and compilers being bound to obey the standards?

In the statement return std::move(name);, what the compiler sees is return f(...); where f(...) is some mysterious function call that returns an rvalue. For all it knows, you could have written return object.optional_name().value();, which is also a mysterious function call that returns an rvalue. There is nothing in the expression std::move(name) that says, “Trust me, this rvalue that I return is an rvalue of a local variable from this very function!”

Now, you might say, “Sure, the compiler doesn’t know that, but what if we made it know that?” Make the function std::move a magic function, one of the special cases where the core language is in cahoots with the standard library.

This sort of in-cahoots-ness is not unheard of. For example, the compiler has special understanding of std::launder, so that it won’t value-propagate memory values across it, and the compiler has special understanding of memory barriers, so that it won’t optimize loads and stores across them.

❌
❌