Consider the below.
#include <string> using std::string; string middle_name () { return "Jaan"; } int main () { string&& danger = middle_name(); // ?! return 0; }
This doesn't compute anything, but it compiles without error and demonstrates something that I find confusing: danger
is a dangling reference, isn't it?
Rvalue references is a small technical extension to the C++ language. Rvalue references allow programmers to avoid logically unnecessary copying and to provide perfect forwarding functions. They are primarily meant to aid in the design of higer performance and more robust libraries.
Among more structured solutions, a popular technique to avoid dangling pointers in C++ is to use smart pointers. A smart pointer typically uses reference counting to reclaim objects. Some other techniques include the tombstones method and the locks-and-keys method.
C++ static code analysis: Immediately dangling references should not be created.
A link or pointer to an instruction, table element, index item, etc. that no longer contains the same content. If the reference is not a currently valid address, or if it is valid but there is no content in that location, it may cause the computer to crash if the software is not programmed carefully.
Do rvalue references allow dangling references?
If you meant "Is it possible to create dangling rvalue references" then the answer is yes. Your example, however,
string middle_name () { return "Jaan"; } int main() { string&& nodanger = middle_name(); // OK. // The life-time of the temporary is extended // to the life-time of the reference. return 0; }
is perfectly fine. The same rule applies here that makes this example (article by Herb Sutter) safe as well. If you initialize a reference with a pure rvalue, the life-time of the tempoary object gets extended to the life-time of the reference. You can still produce dangling references, though. For example, this is not safe anymore:
int main() { string&& danger = std::move(middle_name()); // dangling reference ! return 0; }
Because std::move
returns a string&&
(which is not a pure rvalue) the rule that extends the temporary's life-time doesn't apply. Here, std::move
returns a so-called xvalue. An xvalue is just an unnamed rvalue reference. As such it could refer to anything and it is basically impossible to guess what a returned reference refers to without looking at the function's implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With