c++ - Returning a reference to a class field via local reference - Stack Overflow

admin2025-04-16  10

As I understand, this code is safe:

class Clazz {
public:
    Clazz() {
        holder_[0] = Test(42);
    }

    Test& bar() {
        return holder_[0];
    }

    void foo() {
        const Test& t = bar();
        std::cout << "t has val " << t.getVal() << std::endl;
    }
private:
    std::map<int, Test> holder_;
};

int main() {
    Clazz c;
    c.foo();
}

Would this code still be safe if bar was implemented like this:

Test& bar() {
    Test &t = holder_[0];
    return t;
}
转载请注明原文地址:http://www.anycun.com/QandA/1744783495a87569.html