简体   繁体   中英

C++ temporary object bound to argument and return value const references

I cannot get a clear idea of whether this is legal, even after looking at related questions on SO and reading the C++03 standard page 192 ( http://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf ). Is this legal and safe:

const MyClass& f(const MyClass& arg) {
  return arg;
}

void some_other_function() {
  const MyClass& reference = f(MyClass());
  // Use reference.
}

It seems to me that it is.

As far as I know, you can't do this. While binding a temporary to a const reference is legal C++(and lengthens the lifetime of that temporary -- see GOTW 88 ), further binding a const ref to another const ref doesn't lengthen the lifetime of that temporary.

The quote from page 192( C++03 standard ):

A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call

I think the standard is pretty explicit that using reference after // Use reference. is invalid. I modified your snippet to check it(Mac OS X, clang: Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) ):

#include <iostream>

struct MyClass
{
    ~MyClass()
    {
        std::cout << "~MyClass()" << std::endl;
    }
};

const MyClass& f(const MyClass& arg) {
    std::cout << "f()" << std::endl;
    return arg;
}

int main() {
    const MyClass& reference = f(MyClass());
    std::cout << "main()" << std::endl;
}

It outputs:

f()
~MyClass()
main()

In other words, unless both me and clang developers are misinterpreting the C++ standard, it is illegal.

I was unable to get a clear interpretation from the standard, so I decided to check what's the de facto standard. The following code:

#include <cstdio>

struct MyClass
{
    MyClass() { printf("constructor\n"); }
    ~MyClass() { printf("destructor\n");  }
    MyClass(const MyClass&) { printf("copy\n"); }
    MyClass(MyClass&&) { printf("move\n"); }
};

const MyClass& f(const MyClass& arg) {
    return arg;
}

int main()
{
    {
        printf("before construction\n");
        const MyClass& reference = f(MyClass());
        printf("after construction\n");   
    }
    printf("outside scope\n");
}

Yields:

before construction
constructor
destructor
after construction
outside scope

For MSVC, clang and g++. Seems it is not legal according to our main compiler suppliers.

This question is similar to following question: Pass const Key_Type& to operator[] of std::map

The code below explains what exactly is happening

#include <iostream>


struct MyClass{

  int member;


  MyClass():member(0){
      std::cout<<"MyClass ctr "<<std::endl;
  }

  MyClass(const MyClass& rhs){

      std::cout<<"MyClass copy ctr "<<std::endl;
  }

  ~MyClass(){

      std::cout<<"MyClass dtr"<<std::endl;
      member = -1;
  }
};

void f2(const MyClass& obj){

    std::cout<<"func "<<obj.member<<std::endl;

}   

const MyClass& f3(){ 
    return MyClass(); 
}

MyClass f4(){ 
    return MyClass(); //ideally not a good idea, exception is
    //http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
}

int main()
{
    std::cout << "-----Faulty Case-----------"<<std::endl;

    //reference returned by f3 is local to f3 call and 
    //is destructed as soon as f3() is out of stack
    //and hence the reference in f2() is not valid
    f2( f3() );

    std::cout <<std::endl<< "-----Correct way-----------"<<std::endl;

    //A temporary object is returned by f4 which is then referred by reference in f2.
    //This reference is alive in stack of f2 and hence can be used inside 
    //f2 with valid results.
    //As explained in following article, the refernce should remain
    //alive in stack to use temporary objects.
    //http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
    f2( f4() );

    //note in previous expression, f4 returns by value but still copy ctr is not invoked,
    //this I believe is Return Value Optimization (might be compiler dependent)

    return 0;
}

Output of this program would be:

Executing the program....
$demo 
-----Faulty Case-----------
MyClass ctr 
MyClass dtr
func -1

-----Correct way-----------
MyClass ctr 
func 0
MyClass dtr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM