Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

emplace

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;
};
like image 581
Steger Avatar asked Jun 11 '16 20:06

Steger


1 Answers

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.

like image 74
Barry Avatar answered Nov 15 '22 05:11

Barry