Šimon Tóth’s Post

View profile for Šimon Tóth

C++ Educational Content Creator | 20 years of Software Engineering experience distilled into digestible daily posts

Singletons should be avoided if possible, as they introduce a hurdle for testing. However, sometimes a global state might be the least bad choice. If you need a Singleton, use a simple getter function that returns a reference to a local static variable. Block-scope static variables are initialized in a thread-safe and exception-safe manner. Compiler Explorer link: https://lnkd.in/e8GszGTv #cpp #cplusplus #coding #programming #dailybiteofcpp

  • text
Stephen Channell

CEPHEIS LTD1K followers

2y

Better to avoid "friend" and move the function to an static "instance function". The instance function should use lazy instantiation to allow static initialisation of default (pre-init) state. Mutex lock is best practice to avoid memory leak if heap allocation is used, and called from separate threads concurrently

Like
Reply
Eric Angleton

Angleton Holdings3K followers

2y

Wondering if/what the Rust equivalent is now myself.

Like
Reply
Levon Ghukasyan

Activeloop3K followers

2y

Hey Šimon Tóth, are you targeting to educate advanced programmers or beginners? If you are targeting advanced ones then you need to showcase the real problem If it is for beginners then you need to showcase what is singleton, which problem it solves. What is the tradeoff of using it

Why don't you use a public static function instead of a friend function?

See more comments

To view or add a comment, sign in

Explore content categories