Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pass by reference local variable

I'm new to c++

I have following class:

class User
{
public:
    User(const string& username) {
         m_username = username;
    }

    string username() const {
        return m_username;
    }

    void setUsername(const string &username) {
        m_username = username;
    }

private:
    string m_username;
};

Here is main.cpp code

User *createUser() {
    string username = "someUser";
    User *u = new User(username);
    return u;
}

int main(int argc, char *argv[])
{
    User *u2 = createUser();
    cout << u2->username() << endl;
    return 0;
}

In function createUser() I'm creating local variable username and pass it by reference to User class constructor. When function ends, variable username goes out of scope, therefore value of m_username member of class User should deleted.

But is still accessible outside of this function, e.g. main method prints "someUser" to console.

Why?

like image 344
Teimuraz Avatar asked Feb 03 '16 01:02

Teimuraz


2 Answers

The username local variable in createUser goes out of scope and is deleted.

The m_username member variable in the User instance is a completely separate variable, and it is not deleted at that point, because there's no reason it would be deleted.

This has nothing to do with whether you pass it to the constructor by reference or not.

You might be thinking of a similar but different situation - if m_username was a reference to the local variable (instead of being a completely unrelated variable) you would have a problem:

class User
{
public:
    User(const string& username)
        : m_username(username)
    {
    }

    string username() const {
        return m_username; // <---- Undefined behaviour HERE
        // where the variable that m_username refers to is accessed,
        // but that variable's already been destroyed.
    }

private:
    const string &m_username; // <---- now a reference
};

Here is main.cpp code

User *createUser() {
    string username = "someUser";
    User *u = new User(username);
    return u;
}

int main(int argc, char *argv[])
{
    User *u2 = createUser();
    cout << u2->username() << endl;
    return 0;
}
like image 175
user253751 Avatar answered Nov 11 '22 11:11

user253751


When function ends, variable username goes out of scope, therefore value of m_username member of class User should deleted.

That's not right. I don't see the implementation of your User constructor, but i guess it just does a copy of given string. m_username has no further link to your local variable, it's an own instance.

like image 2
Youka Avatar answered Nov 11 '22 11:11

Youka