Sitemap
Samira

Samira

Backend C++ engineer passionate about solving complex problems with C++ and multi-threading, optimizing apps for advanced research in biotechnology.

๐”๐ง๐๐ž๐ซ ๐ญ๐ก๐ž ๐‡๐จ๐จ๐: ๐„๐ฑ๐ฉ๐ฅ๐จ๐ซ๐ข๐ง๐  ๐ˆ๐ง๐ข๐ญ๐ข๐š๐ฅ๐ข๐ณ๐ž๐ซ-๐‹๐ข๐ฌ๐ญ ๐œ๐จ๐ง๐ฌ๐ญ๐ซ๐ฎ๐œ๐ญ๐จ๐ซ๐ฌ ๐ข๐ง ๐‚++

3 min readFeb 16, 2025

--

โŒAvoid initializing containers with initializer_list if you canโŒ

๐ŸŽฏEver wondered what really happens under the hood when a C++ container uses an initializer-list constructor that accepts an std::initializer_list type?

๐Ÿ”ด๐–๐ก๐š๐ญ ๐ข๐ฌ ๐ฌ๐ญ๐::๐ข๐ง๐ข๐ญ๐ข๐š๐ฅ๐ข๐ณ๐ž๐ซ_๐ฅ๐ข๐ฌ๐ญ<T>?

The standard-library type std::initializer_list<T> is used to handle variable-length {}-lists. Its ๐ฆ๐จ๐ฌ๐ญ ๐จ๐›๐ฏ๐ข๐จ๐ฎ๐ฌ ๐ฎ๐ฌ๐ž is to to enable initializer lists for user-defined containers, though it can also be used directly. When we use a {}-list, such as {1, 2, 3}, the compiler creates an object of type std::initializer_list<T> to pass to the constructor.

๐Ÿ”—Links to a simplified container implementation demonstrating ๐จ๐ง๐ฅ๐ฒ an initializer-list constructor (skipping edge cases and exception handling is intentional to make the example concise).

โœ…godbolt.org/z/MW4c7ThMh 
โœ…godbolt.org/z/h1j1KbGf9

๐Ÿ”Iโ€™d like to highlight some key concepts based on the follwoing code:

#include <memory>

template <typename T>
class Container
{
public:
Container(std::initializer_list<T> lst):
m_size{ lst.size() },
m_data{ static_cast<T*>(::operator new(m_size * sizeof(T))) }
{
for (size_t i = 0; auto & item: lst)
{
// ๐ฉ๐ฅ๐š๐œ๐ž๐ฆ๐ž๐ง๐ญ ๐ง๐ž๐ฐ
new (std::addressof(m_data[i++])) T{ item };
}
}
~Container()
{
if (m_data)
{
for (size_t i = m_size; i-- > 0; )
{
m_data[i].~T();
}
::operator delete(m_data);
m_data = nullptr;
}
}

private:
size_t m_size;
T* m_data;
};

1๏ธโƒฃ๐จ๐ฉ๐ž๐ซ๐š๐ญ๐จ๐ซ ๐ง๐ž๐ฐ is used โ€” not to be confused with the ๐ง๐ž๐ฐ ๐จ๐ฉ๐ž๐ซ๐š๐ญ๐จ๐ซ โ€” to allocate raw memory for type ๐“ without invoking its constructor. This is especially useful when ๐“ lacks a default constructor or has multiple overloaded constructors, because it allows us to selectively initialize objects via placement new based on the provided initializer list.

2๏ธโƒฃinitializer_list doesnโ€™t support subscripting but offers begin(), end(), size() members. Inside the for-each loop, placement new ๐œ๐จ๐ฉ๐ฒ ๐œ๐จ๐ง๐ฌ๐ญ๐ซ๐ฎ๐œ๐ญ๐ฌ an object of type ๐“ with the value ๐’Š๐’•๐’†๐’Ž at the specified address in ๐’Ž_๐’…๐’‚๐’•๐’‚. This is where the actual copying of elements from the initializer_list into the containerโ€™s internal memory occurs. This use of a constructor is known as ๐ฉ๐ฅ๐š๐œ๐ž๐ฆ๐ž๐ง๐ญ ๐ง๐ž๐ฐ.

3๏ธโƒฃTypically, it is unnecessary and potentially error-prone to explicitly call a destructor. But, there are rare but important cases where a destructor must be called explicitly, such as in the destructor of the ๐‚๐จ๐ง๐ญ๐š๐ข๐ง๐ž๐ซ class. Here, the notation ๐ฆ_๐๐š๐ญ๐š[๐ข].~๐“() is used to explicitly invoke Tโ€™s destructor for each element in the container. Eventually we use ๐จ๐ฉ๐ž๐ซ๐š๐ญ๐จ๐ซ ๐๐ž๐ฅ๐ž๐ญ๐ž โ€” not to be confused with ๐ญ๐ก๐ž ๐๐ž๐ฅ๐ž๐ญ๐ž ๐จ๐ฉ๐ž๐ซ๐š๐ญ๐จ๐ซ. Operator delete does not implicitly call destructors; it only deallocates memory.

Get Samiraโ€™s stories inย yourย inbox

Join Medium for free to get updates fromย thisย writer.

๐Ÿ”ดDestruction Process in the custom Container class:

โœ…Explicit Destructor Calls for Each Element

The loop iterates over the elements in reverse order (which can be important if the destruction order matters) and explicitly calls each elementโ€™s destructor using m_data[i].~T();. This ensures that if T manages any resources (like dynamically allocated memory, file handles, etc.), its destructor will properly release those resources.

โœ…Deallocation of the Raw Memory

After all the elements have been properly destroyed, ::operator delete(m_data); is called. This frees the memory that was previously allocated with ::operator new(m_size * sizeof(T)) in the constructor. So, the destructor first makes sure that each T instance cleans up its internal resources, and then it releases the raw memory used to store these instances.

๐Ÿ˜You might be wondering ๐ฐ๐ก๐ฒ ๐ฐ๐ž ๐๐จ๐งโ€™๐ญ ๐ฎ๐ฌ๐ž ๐ฌ๐ญ๐::๐ฆ๐จ๐ฏe ๐ญ๐จ ๐š๐ฏ๐จ๐ข๐ ๐œ๐จ๐ฉ๐ฒ๐ข๐ง๐  ๐ข๐ง ๐ญ๐ก๐ž ๐Ÿ๐ข๐ซ๐ฌ๐ญ ๐ฉ๐ฅ๐š๐œ๐ž:

new (std::addressof(m_data[i++])) T{๐ฌ๐ญ๐::๐ฆ๐จ๐ฏe(item)};

Because elements in an initializer_list are ๐ข๐ฆ๐ฆ๐ฎ๐ญ๐š๐›๐ฅ๐ž, we cannot apply a move constructor to them. Using std::move would simply fall back to copying the elements!

๐Ÿ”‘Now, if you click on the link and run the code, youโ€™ll notice the differences between using initializer_list, push_back, and emplace_back in a container like std::vector. Particularly, initializer_list incurs ๐ž๐ฑ๐ญ๐ซ๐š ๐œ๐จ๐ฉ๐ข๐ž๐ฌ!

#cpp #iLoveCpp #cplusplus

โžก๏ธ Resources :

The C++ Programming Language by Bjarne Stroustrup 4th edition.

--

--

Samira
Samira

Written by Samira

Backend C++ engineer passionate about solving complex problems with C++ and multi-threading, optimizing apps for advanced research in biotechnology.