Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens in C++ when I pass an object by reference and it goes out of scope?

Tags:

c++

I think this question is best asked with a small code snippet I just wrote:

#include <iostream>

using namespace std;

class BasicClass
{
public:
    BasicClass()
    {
    }
    void print()
    {
        cout << "I'm printing" << endl;
    }
};

class FriendlyClass
{
public:
    FriendlyClass(BasicClass& myFriend) :
        _myFriend(myFriend)
    {
    }
    void printFriend()
    {
        cout << "Printing my friend: ";
        _myFriend.print();
    }
private:
    BasicClass& _myFriend;
};

int main(int argv, char** argc)
{
    FriendlyClass* fc;
    {
        BasicClass bc;
        fc = new FriendlyClass(bc);
        fc->printFriend();
    }
    fc->printFriend();
    delete fc;
    return 0;
}

The code compiles and runs fine using g++:

$ g++ test.cc -o test
$ ./test
Printing my friend: I'm printing
Printing my friend: I'm printing

However, this is not the behavior I was expecting. I was expecting some sort of failure on the second call to fc->printFriend(). Is my understanding of how the passing/storing by reference works incorrect or is this something that just happens to work on a small scale and would likely blow up in a more sophisticated application?

like image 812
Corey D Avatar asked Sep 29 '11 21:09

Corey D


1 Answers

When you store a reference to an object that has ended its lifetime, accessing it is undefined behavior. So anything can happen, it can work, it can fail, it can crash, and as it appears I like to say it can order a pizza.

like image 89
K-ballo Avatar answered Oct 10 '22 20:10

K-ballo