C++ Small string optimizations

One size does not fit all
One size does not fit all

What is “small string optimization”?

Standard C++  string stores its data on the heap. But that is only true if the string  grows over an implementation-dependent size. That predefined  size for std::string is/was 15 for MSVC and GCC and 23 for Clang.  That is: C++ string stays “small”, if  you have not asked for bigger than 15/23 sized strings. The string will not attempt to grow its storage on the heap if it can stay small.

Heap memory allocations/de-allocations are taking a lot of time when compared to most standard C run time calls.

Thus if you avoid them your program will run faster and will consume less memory. Continue reading “C++ Small string optimizations”

C++ Polymorphism with no inheritance

Different products but same messages
Working Wandbox-ed modern C++ code, is HERE.

C++ Polymorphism with no inheritance is by no means, somewhat advanced concept. But, this is just because it is (in C++) based on different concepts v.s. some other good and popular languages where it is in the foundations  of the language design.

For example in GO LANG polymorphism is definitely not tied to inheritance. And this is one very much popular and good programing language, indeed. Continue reading “C++ Polymorphism with no inheritance”

C++ The Modern Factory

Vintage car factory
We can do better.

I think I have architected, designed and implemented, what might be (a bit) better  Factory Pattern. Of course, I am pretty sure someone else has discovered the same variation.

Of all the patterns, very often, I was particularly bothered with “classical” aka legacy, Factory. Yes, once implemented, you can relatively easily make it create new “things”, but on the design and usability level, to me,  it does not look very flexible and expandable.

On the C++ level it requires code repetition and use of  smart pointers. In essence these two combined, somehow do not look to me like modern C++ at all. Continue reading “C++ The Modern Factory”

c++ Play it only once Sam

Just how many times you have admitted to yourself it was rather foolish to think of globals in C++ as “a simple thing” 🙂 After all: What could possibly go wrong? If you know what I am talking about please proceed.

As it turns out many things can and will go wrong, with what you think of as C++ global variables and functions. I am sure every now and then, you are wondering why is this singleton not a singleton, why is this function called more than once,  and how it is, that nobody seems to care?

After many years of various coding idioms, that handle static linkage and global variables, and the famous “Singleton Pattern” implementations, may I be so bold to remind you: you do not have to dance around these issues any more.

It is 2018 after all. Continue reading “c++ Play it only once Sam”