In the previous post about lazy initialisation, we showed examples and differences between using raw pointers, unique_ptr and std::optional to store the object and create it later. However, we implemented the samples from the perspective of single-threaded scenarios.
In this post, we’ll try to fill the gap and show you how to make your lazy objects available in a multithreading environment.
Lazy initialisation is one of those design patterns which is in use in almost all programming languages. Its goal is to move the object’s construction forward in time. It’s especially handy when the creation of the object is expensive, and you want to defer it as late as possible, or even skip entirely.
std::visit is a powerful utility that allows you to call a function over a currently active type in std::variant. It does some magic to select the proper overload, and what’s more, it can support many variants at once.
Let’s have a look at a few examples of how to use this functionality.
How do you initialise a string member in the constructor? By using const string&, string value and move, string_view or maybe something else?
Let’s have a look at possible options.
Intro Below there’s a simple class with one string member. We’d like to initialise it.
For example:
class UserName { std::string mName; public: UserName(const std::string& str) : mName(str) { } }; As you can see a constructor is taking const std::string& str.
Writing a factory method might be simple:
unique_ptr<IType> create(name) { if (name == "Abc") return make_unique<AbcType>(); if (name == "Xyz") return make_unique<XyzType>(); if (...) return ... return nullptr; } Just one switch/if and then after a match you return a proper type.
But what if we don’t know all the types and names upfront?
Let’s see pimpl and its alternatives in a real application! I’ve implemented a small utility app - for file compression - where we can experiment with various designs.
Is it better to use pimpl or maybe abstract interfaces? Read on to discover.
Intro In my previous post I covered the pimpl pattern.
Have you ever used the pimpl idiom in your code? No matter what’s your answer read on :)
In this article I’d like to gather all the essential information regarding this dependency breaking technique. We’ll discuss the implementation (const issue, back pointer, fast impl), pros and cons, alternatives and also show examples where is it used.
Let’s look at the following problem:
We are designing a drawing application. We want some objects to be automatically scaled to fit inside parent objects. For example: when you make a page wider, images can decide to scale up (because there’s more space). Or if you make a parent box narrower image needs to scale down.