Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will temporary object be deleted if there is no const reference to it?

Lets take a look to this two functions:

std::string get_string()
{
    std::string ret_value;
    // Calculate ret_value ...
    return ret_value;
}

void process_c_string(const char* s)
{
    std::cout << s << endl;
}

And here are two possible calls of process_c_string with argument returned by get_string.

  1. Without binding const reference to the returned object of get_string.

    process_c_string(get_string().c_str());
    
  2. With binding const reference to the returned object of get_string.

    const std::string& tmp_str = get_string();
    process_c_string(tmp_str.c_str());
    

I know that second way is valid, but what about the first one, what does standard say about this case? Will the temporary object returned by get_string be deleted before process_c_str finished because of there is no const reference to it?

Note: The both versions are ok in MSVC.

like image 845
Mihran Hovsepyan Avatar asked Jan 26 '12 13:01

Mihran Hovsepyan


People also ask

Can a const reference refer to a non const object?

No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .

Does const reference extend lifetime?

In the by-reference case, we get a const Base& reference that refers to a Derived object. The entire temporary object, of type Derived , is lifetime-extended.

Can const reference be modified?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.


1 Answers

The lifetime of the temporary extends for the length of the full expression in which it was created. In your case, the temporary will be destroyed but only after the call to process_c_string completes. As long as the function does not store the pointer for later use, you are fine.

In the second case (binding of reference), the lifetime of that temporary is extended to be the scope of the reference, but I would advise against that pattern in this particular case. You get the same effect by creating a local string initialized with the temporary and the code is simpler. (From a performance point of view, all compilers elide the potential extra copy in the code, so the cost would be the same)

like image 62
David Rodríguez - dribeas Avatar answered Nov 15 '22 05:11

David Rodríguez - dribeas