Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do rvalue references allow dangling references?

Tags:

c++

c++11

rvalue

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?

like image 800
Andres Jaan Tack Avatar asked Sep 15 '10 09:09

Andres Jaan Tack


People also ask

What are rvalue references good for?

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.

How do you prevent dangling references?

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.

Can dangling references exist in C++?

C++ static code analysis: Immediately dangling references should not be created.

What happens when we access dangling reference?

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.


1 Answers

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.

like image 50
sellibitze Avatar answered Oct 16 '22 18:10

sellibitze