C++ emplace()
The emplace() method of the std::queue<T,Container> container adaptor constructs a new element directly in the underlying container at the back of the queue, forwarding the provided arguments to the constructor of T. Because the object is constructed in place, this can improve performance for types with expensive copy or move operations.
Syntax
queue.emplace(args...)
Parameters:
args...(variadic template parameters): Arguments forwarded to construct the new element of typeT.
Return value:
Since C++17: A reference to the inserted element (the value returned by the underlying container’s emplace_back method).
Example 1: Enqueueing log entries into a queue
In this example, log messages are constructed in place and enqueued for later processing:
#include <iostream>#include <queue>#include <string>struct LogEntry {std::string level;std::string message;LogEntry(std::string lvl, std::string msg): level(std::move(lvl)), message(std::move(msg)) {}};int main(){std::queue<LogEntry> logs;logs.emplace("INFO", "Application started");logs.emplace("WARN", "Low disk space");logs.emplace("ERROR", "Out of memory");while(!logs.empty()){const auto& entry = logs.front();std::cout << "[" << entry.level << "] " << entry.message << "\n";logs.pop();}}
The output of this code is:
[INFO] Application started[WARN] Low disk space[ERROR] Out of memory
Example 2: Constructing tasks in a task queue
In this example, tasks with multiple constructor parameters are constructed directly inside the queue:
#include <iostream>#include <queue>#include <functional>struct Task {int id;std::string description;Task(int i, std::string desc): id(i), description(std::move(desc)) {}void run() const { std::cout << "Running task #" << id << ": " << description << "\n"; }};int main(){std::queue<Task> taskQueue;taskQueue.emplace(1, "Load configuration");taskQueue.emplace(2, "Initialize modules");taskQueue.emplace(3, "Start services");while(!taskQueue.empty()){taskQueue.front().run();taskQueue.pop();}}
The output of this code is:
Running task #1: Load configurationRunning task #2: Initialize modulesRunning task #3: Start services
Codebyte Example: Buffering sensor data with emplace
In this example, sensor readings are constructed and enqueued as soon as they arrive, minimizing overhead:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours