Search code examples
c++stlemplace

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


I must be missing one of the finer points regarding emplace() and friends. Here's a complete, minimal example that reproduces the problem with 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;
};

Solution

  • In emplace_back, the container is the one that constructs the Bar. But that constructor is private and the container is not a friend, so it fails.

    But push_back(*this) is equivalent to push_back(Bar(*this)). That is, it's the Foo that's doing the construction and it is a friend.