Search code examples
c++referencereturn

Is it safe or even possible to use a reference to an object that is returned by a (member) function?


I have a class storing a bunch of values that can change throughout the program and a member function, that calculates and returns a matrix, based on those values.

I also have a function that requires a const pointer to the first float of such a matrix.

I don't want to manually create a local matrix somewhere. Instead i want to simultaneously update and pass it to said function straight from the class.

So, instead of this:

glm::mat4 matrix = myClass.calculateMatrix();

functionThatneedsMatrix(&matrix [0][0]);

can i do this?

functionThatneedsMatrix(&myClass.calculateMatrix()[0][0]);

And if yes, what would be the scope of that matrix?


Solution

  • A temporary lives until the end of the full expression in which it was created so in your case the prvalue returned from calculateMatrix lives until the ; (after functionThatneedsMatrix returns) . So yes, it is safe to use it this way.

    functionThatneedsMatrix(&myClass.calculateMatrix()[0][0]) ;
    //                                                        ^
    //                                                        |
    //                                                temporary lifetime ends here,
    //                                                after functionThatneedsMatrix returns
    

    A possible UB case is if functionThatneedsMatrix returns or stores that pointer in a way that it is accessible after the function call ends:

    int* p = functionThatneedsMatrix(&myClass.calculateMatrix()[0][0]) ;
    //       ^
    //       if it returns the pointer value it received as parameter
    
    // p is a dangling pointer at this time
    
    int a = *p; // Undefined behavior