Is there any difference between std :: stack :: push () and std :: stack :: emplace () in this case?

Take a look at this code:

struct Dummy
{
    int bla;
    int blabla;
    char character;

    Dummy (int b, int bb, char c)
        : bla(b), blabla(bb), character(c)
    {}
};

std::stack<Dummy> s;
Dummy dummy;
s.push(dummy);   // (1)
s.emplace(dummy);   // (2)

I do not see the difference between (1)and (2). I know that it emplace()is useful when you provide arguments for the constructor of the object to be added, for example:

s.emplace(1, 2, 'c');

but I do not know what the difference is when I described, because the and tags push(), and emplace()must refer to a local object dummyand create a new object using the copy ctor or something like that, you want to create push()any temporary objects in the process?

+4
source share
2 answers

Times will not be. For a standard, pushit looks like this:

void push(const value_type& x) { c.push_back(x); }
void push(value_type&& x) { c.push_back(std::move(x)); }

emplace :

template <class... Args>
void emplace(Args&&... args) { 
    c.emplace_back(std::forward<Args>(args)...);
}

c - , - deque<T>. , , push, push(const Dummy&), Dummy(const Dummy&). emplace_back(Dummy&), Dummy(Dummy&).

- . , . , (1) (2).

, ( ), .

+5

, value_type, emplace , , push, .

emplace: -

. , .. . , .

0

All Articles