关于在 C++ 中正确管理本地类中的引用成员的问题

问题描述 投票:0回答:0

我得到垃圾值的原因是因为以下还是我错了?

Other 对象 o 作为参数传递给 Inner 构造函数,在创建 Inner 对象之后但在 get_a_value 成员函数结束之前超出范围。因此,Inner 对象中的引用成员 m_o 就变成了悬空引用,指向一个不再存在的对象。

#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';
}

上面代码的输出是:

o.j 3

o.j 3

m_o.j 3

623661

c++ class reference local dangling-pointer
© www.soinside.com 2019 - 2024. All rights reserved.