Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does gcc have a extension overload for std::vector::emplace_back?

According to cppreference, std::vector::emplace_back has only one signature, which is:

template< class... Args >
reference emplace_back( Args&&... args );

And in the description, it says emplace_back is supposed to forward each of its arguments to the constructor of the type in the vector. However, when I tested the following code using gcc 12.2, it successfully compiles:

#include <iostream>
#include <vector>

class Foo
{
public:
    int x;
    int y;
    Foo(int x, int y) : x(x), y(y)
    {}
};

int main()
{
    std::vector<Foo> foos;
    Foo foo(1, 2);
    foos.push_back(std::move(foo));
    foos.emplace_back(foo); // weird
}

(See on compiler explorer)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I expected the line foos.emplace_back(foo); to fail the compilation. It seems as if emplace_back has this overload:

template< class T >
reference emplace_back( T& arg );

which isn’t mentioned in the documentation. Am I missing something or is this just a compiler extension?

>Solution :

template< class... Args >
reference emplace_back( Args&&... args );

can deduced to something like (with Args = Foo&)

reference emplace_back( Foo& && args[0] );

which collapse to

reference emplace_back( Foo& args[0] );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading