0

Is the reason why I got a garbage value because of the following or am I wrong?

the Other object o passed as an argument to the Inner constructor, goes out of scope after the Inner object has been created, but before the end of the get_a_value member function. Therefore, the reference member m_o in the Inner object becomes a dangling reference, referring to an object that no longer exists.

#include <iostream>

class Other
{
private:
    int j = 3;
    friend class TEST; //class TEST is a friend of the class Other
};

class TEST
{
private:
    int i = 10;
public:
    int get_a_value() const //a member function of TEST
    { //member function begins
        struct Inner

        {
            Inner(Other o) : //constructor
                /*m_o{ o } it is correct too */ m_o( o )
            {
                std::cout << "o.j " << o.j << '\n';
                std::cout << "m_o.j " << this->m_o.j << '\n';
            }
            int get_other_value() //other in the name of the member function refers to Other class defined above
            {
                return this->m_o.j;
            }
            Other& m_o;
        };


        Other o; //local variable of member function get_a_value
        std::cout << "outside o.j " << o.j << '\n';
        Inner i(o); //local variable of member function get_a_value
        return i.get_other_value();
    }//member function ends

};


int main()
{
    TEST t;
    std::cout << t.get_a_value() << '\n';
}

The output of code above is :

outside o.j 3

o.j 3

m_o.j 3

623661

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Sami
  • 513
  • 4
  • 11
  • 1
    Yes. You are accessing a dangling reference, which is Undefined Behavior. You may get a garbage number or a program crash or something worse. – Drew Dormann Mar 05 '23 at 21:57
  • Thanks for the response. If I define constructor's argument as reference type (Other& o), then m_o points to the actual object (not copy) 'other' defined inside the get_a_value member function and this reference (m_o) to that value will be valid until the method execution finishes which means after "std::cout << t.get_a_value() << '\n';" and if I used that value , then I would again end up having dangling pointer, am I right? – Sami Mar 05 '23 at 22:01
  • 1
    You will have a dangling reference after `Other o` goes out of scope. You will not have a dangling pointer because this code has no pointers other than `this`. – Drew Dormann Mar 05 '23 at 22:04

0 Answers0