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

question on properly managing reference members in a local class in C++

提问人:Sami 提问时间:3/6/2023 最后编辑:Drew DormannSami 更新时间:3/6/2023 访问量:48

问:

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

作为参数传递给 Inner 构造函数的 Other 对象 o 在创建 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++ 引用 本地 悬空指针

评论


答: 暂无答案