Why pass a temporary variable to const ref in ctor?

// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout << p->d_member << std::endl;

    return 0;
}

      

Foo accepts const ref in it ctor for int and I passed a temporary int to it. temp is destroyed after a new one. Why can I still print d_member?

+3


source to share


3 answers


The constructor initialization list copies the integer argument to the member variable. The lifetime of your member variable is the lifetime of your object.



+6


source


As mentioned earlier with reference variable, your constructor call simply copies the value from the reference parameter const

(and it doesn't even matter if you pass it by reference or value).

You will have a different situation if your member variable is a reference like

struct foo
{
    const int& d_member; // <<<< reference member variable

    foo(const int & in): d_member(in){};
};

      



In this case, accessing d_member

after your visibility block changes the undefined behavior:

{
    int temp = 5;
    p = new foo(temp);
}

std::cout << p->d_member << std::endl; // <<<<  Undefined behavior

      

+6


source


Yes, it was temp

destroyed, but before that it was copied during initialization d_member(in)

. So nothing happens here.

+3


source







All Articles