std::stack::emplace(3)

๐Ÿ“ฆ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

๐Ÿ’– NAME ๐Ÿ’–

Okay so bestie, welcome to std::stack::emplace(3) โ€” straight out of the C++ Standard Libary manual. The name is so iconic it said it twice: std::stack::emplace - std::stack::emplace. ๐Ÿ’…


โœจ Synopsis โœจ

Here's the signature timeline, and yes the since / until labels are doing main character energy:

template< class... Args >                  (since C++11)
void emplace( Args&&... args );            (until C++17)
template< class... Args >                  (since C++17)
decltype(auto) emplace( Args&&... args );

So what does it do? Pushes a new element on top of the stack. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments as supplied to the function.

Effectively calls c.emplace_back(std::forward<Args>(args)...);. ๐Ÿซถ


๐Ÿงš Parameters ๐Ÿงš

  • args โ€” arguments to forward to the constructor of the element.

๐ŸŽ€ Return value ๐ŸŽ€

  • Until C++17: (none).
  • Since C++17: The value or reference, if any, returned by the above call to Container::emplace_back.

๐Ÿฆ‹ Complexity ๐Ÿฆ‹

Identical to the complexity of Container::emplace_back. No extra mystery math, just vibes. ๐Ÿงฎโœจ


๐ŸŒธ Example ๐ŸŒธ

Run this code, bestie:

       // Run this code

        #include <iostream>
        #include <stack>

        struct S
        {
            int id;

            S(int i, double d, std::string s) : id{i}
            {
                std::cout << "S::S(" << i << ", " << d << ", \"" << s <<
       "\");\n";
            }
        };

        int main()
        {
            std::stack<S> stack;
            const S& s = stack.emplace(42, 3.14, "C++"); // for return value
       C++17 required
            std::cout << "id = " << s.id << '\n';
        }

๐Ÿ–จ๏ธ Output ๐Ÿ–จ๏ธ

S::S(42, 3.14, "C++")
id = 42

๐Ÿ’… Defect reports ๐Ÿ’…

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • LWG 2783 โ€” applied to C++17. Behavior as published: emplace returned reference, breaking compatibility with pre-C++17 containers. Correct behavior: returns decltype(auto). Periodt.

๐ŸŒˆ See also ๐ŸŒˆ

  • push โ€” inserts element at the top (public member function).
  • pop โ€” removes the top element (public member function).

Okay that's the whole page, bestie. Mwah ๐Ÿ’‹ โ€” this vibe was served from http://cppreference.com, dated 2024.06.10, for std::stack::emplace(3). ๐Ÿซถ

๐Ÿ“ฆ where this page comes from