admin管理员组

文章数量:1418705

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

本文标签: cReturning a reference to a class field via local referenceStack Overflow