G++ 4.9.3 抱怨好友 ctor 是私有的 .emplace_back(),但喜欢 .push_back()

g++ 4.9.3 complains that friended ctor is private with .emplace_back(), but likes .push_back()

本文关键字:back emplace push 喜欢 好友 ctor G++      更新时间:2023-10-16

我一定错过了关于emplace()和朋友的一个细节。下面是一个完整的最小示例,重现了 g++ 4.9.3 的问题:

class Foo
{
public:
    class Bar
    {
    private:
    friend class Foo;
        Bar(Foo &foo) : foo(foo) {}
        Foo &foo;
    };
    Bar &getBar()
    {
        //bars.push_back(*this);        // works fine
        bars.emplace_back(*this);       // Foo::Bar::Bar(Foo&) is private
        return bars.back();
    }
private:
    std::vector<Bar> bars;
};

emplace_back中,容器是构造Bar的容器。但是该构造函数是私有的,容器不是友元,因此它会失败。

push_back(*this)相当于push_back(Bar(*this)).也就是说,是Foo在做建设,它是朋友。

    bars.emplace_back(*this);

延迟对构造函数的调用Bar(Foo&) std::vector::emplace_back() 。该函数没有调用Bar(Foo&)的访问权限。

另一方面

    bars.push_back(*this);

在调用 std::vector::push_back() 之前调用构造函数Bar(Foo&)。这不是问题,因为FooBar friend