Lazy initialisation in C++ and Multi-threading

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.

READ MORE...

Lazy Initialisation in C++

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.

READ MORE...

How to Initialize a String Member

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.

READ MORE...

Factory With Self-Registering Types

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?

READ MORE...

The Pimpl Pattern - what you should know

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.

READ MORE...

Applying the Strategy Pattern

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.

READ MORE...