Floating point numbers
C++
General purpose resources
Singleton
Singleton problems
In Are singletons really that bad? it is summarized that a Singleton:
-
Grants global access to an object.
-
Enforces that only one instance of an object can ever exist.
In What are drawbacks or disadvantages of singleton pattern?, the most voted answer on the most voted question about the topic, they say:
-
That are used as a global (which is allegedly bad because the dependencies are hidden "instead of exposing them through the interfaces", and "[m]aking something global to avoid passing it around is a code smell").
-
That break the single responsibility principle because control their own creation and destruction.
-
That cause parts of the application to be "tightly coupled", which is an issue when testing them.
-
That hold state for the whole duration of the application, which can be an issue again on unit tests.
The 4 points seem fine, but a bit redundant, and can be summarized as that:
-
It causes issues with testing, because either the state of a unit test is dependent on what a previous test did, or because you cannot isolate the code that you want to test from the code of the singleton.
-
// the "reason about the code" argument? I’m not sure
Singleton acceptable cases
From On design patterns: When should I use the singleton?, an interesting quote:
Logging is a specific example of an "acceptable" Singleton because it doesn’t affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."
Another good example would a watchdog manager: "clients" (users of the class) periodically notify the manager that they are alive, or report failure, but the fact that clients notify the manager is irrelevant for their behavior and execution (unless one really wants to assert during the tests for such behavior).
Observer
A delegate implementation that is able to bind indistinguisably to a free function and a member function without performance overhead. It uses pre-C++ 11 techniques, but it’s very understandable and well explained on the initial steps of it, covering the mess of pointers to member.
The followup from the author of EnTT.
Orthodox C and C "style" for game development
Seems to come mostly from the game industry. The page has some exposition and some discussion. It amusingly mentions Qt as part of the examples section.
Runtime polymorphism (Sean Parent)
-
Sean Parent: Value Semantics and Concepts-based Polymorphism (CppNow 2012)
-
https://www.reddit.com/r/cpp/comments/cikmhh/implemented_sean_parents_polymorphic_value_types/
-
https://gist.github.com/mrkline/114fa9963a6615231c40247e129c21b4
-
https://github.com/ericprud/sean-parent-concept-based-polymorphism
From the reddit post, Parent has a comment:
Every heap allocation/deallocation for a small object costs as much as copying 10K of data. A single atomic increment/decrement costs as much as copying 32 words of data.
There are still a lot of developers who think every object should have a pure
virtual interface and be allocated with make_shared
. Some too young to know
better, some who have an outdated mental model of modern hardware, and some who
come from reference semantic languages (ObjC, Java,… ). Memory access outside
of cache is slow. Until I can comfortably do everything at 120fps I’ll keep
pushing against this.
And this Compiler Explorer link to an example of implementing dynamic cast for runtime-polymorphism: https://godbolt.org/z/D01us8
Extensibility and customization of classes beyond inheritance
https://www.reddit.com/r/cpp/comments/w1f3ph/upside_down_polymorphic_inheritance_leveraging/ Using standard variant/visit to visitate values that inherit from different possible classes. Since things are in a variant, is not as flexible as type erasure libraries, as the types need to be known in advance. Also, it uses an ugly id.
Mateusz Pusz “Effective replacement of dynamic polymorphism with std::variant”. It uses variant and visitation to dispatch to the event implementation of a state machine. It shows up to 5 possible implementations, with the first two being based on virtual functions.
https://www.fluentcpp.com/2021/01/29/inheritance-without-pointers/
Contains a few simple idioms to move to value semantics. The solution still
requies an interface class, though.
"It is interesting to note that in modern C++ →
does not always means
“pointer”. For example std::optional, that has value semantics, also provides an
operator→ to access its underlying data."
Value semantics
Visitor
-
https://www.fluentcpp.com/2022/02/09/design-patterns-vs-design-principles-visitor/ Article from Jonathan Boccara. Covers the basic idea of a visitor with a classic double dispatch with virtual functions, but also mentions the variant visitor and Meyer’s Item 32 in More Effective C++.
-
https://stackoverflow.com/questions/57598253/a-stdvisit-like-function-for-visiting-over-polymorphic-types A simple but nice enough compromise for using a variant and the standard visit function to dispatch objects to an overloaded function taking exactly the pointer of the object. It’s not very sophisticated, but I think it’s KISS enough and efficient enough to be the answer to (de)serializing widgets that I’ve been looking for.
-
https://stackoverflow.com/questions/11796121/implementing-the-visitor-pattern-using-c-templates Some variadic template magic to reduce the boilerplate in some visitable or visitor classes.
Compile time string manipulation
https://github.com/fmtlib/fmt/blob/dd0b72e1ee393f1eeac7393dc37f909b76239317/include/fmt/format.h#L3403 https://github.com/fmtlib/fmt/blob/dd0b72e1ee393f1eeac7393dc37f909b76239317/test/format-test.cc#L1708 https://www.reddit.com/r/cpp/comments/s3aosn/how_we_used_c20_to_eliminate_an_entire_class_of/ (consteval trick to inspect the arguments of a function at compile time)
https://www.foonathan.net/2022/01/compile-time-codegen/ Treat input strings at compile time (e.g. regexp, DSL) to convert that to code. The example is compile-time "compilation" of Brainfuck.
Special member functions
https://www.foonathan.net/special-member-chart/ https://www.foonathan.net/2019/02/special-member-functions/
The issue with -Wdeprecated-copy and Qt headers was due to how the copy
constructor is/was created implicitly. In newer versions still is, but it causes
a warning, and using = default
is the solution in many cases. See:
https://codereview.qt-project.org/c/qt/qtbase/+/272258
GUI to pure data and the other way around problem
In Moebius Toolkit I have two use cases where, roughly speaking, I want to have a data structure become a GUI structure, and the other way around.
The first situation that I encountered was the structure defined by UIC from the
UI file created by Qt Designer. I want the inputs from the user, which all are
automatically gruped in a Ui::SomeType
struct, where each control is a pointer
of some QWidget
subclass, to be converted to a pure data POD struct (so
roughly speaking a QLineEdit becomes a QString, a QCheckBox a boolean, etc).
The second situation is that I will have plenty of classes for the IE data formats, and I will like to have inputs on the GUI to visualize and edit those values.
Code generation would probably do it, but it seems there are crazy libraries doing some magic that kind of gets some reflection from thin air:
This can allow to iterate through some aggregate type (like the one generated by UIC), but it can’t of course generate a class with with QString and int from QLineEdit and QSpinBox. But maybe it can help in the iteration to serialize one to the other!
Remember that I’ll probably have always the issue of the fact that there are 2 certain spinboxes in a control, and that I want to choose the one or the other based on if the spinbox is hidden or not. This is too app-specific to be nicely fixed in any reasonable way.
Qt 6
Procedural dungeon generation
https://www.reddit.com/r/roguelikedev/comments/mm3nks/improved_bsp_dungeon_algorithm/ Besides some very good screnshots, it has a few interesting tips, like joining rooms by merging them instead of just connecting them by a corridor. Also, a hint on how to connect them.
https://eskerda.com/bsp-dungeon-generation/ Contains a very nice demo and the JS code is fairly understandable.
Random number generators
Some answers of varied opinions on scaling rand(). It includes one answer about assessing a bit on the quality of rand and modulo (the lack of evenness is not that bad) instead of just jumping to C++11.
rand()
considered harmful. The talk from STL who mostly covers some of the usual
gotchas with the old ways and tips for the new ways. He mentions:
* Avoid constructing the engine (e.g. Mersenne Twister) multiple times as it
holds a lot of state.
* Building the distribution (e.g. uniform_int_distribution) each time is fine
(e.g. inside a helper function that receives the range of min/max numbers as
parameter).
* The mt19937 starts repeating after 2 to the (19937-1) times, so impossible to
detect periodicity.
* There is no need to use seed_seq
to seed the engine with 8 calls to the
random_device
(I did this once when implementing a random analytics ID
because that seemed recommended online). Just seeding once is fine:
random_device device; mt19937 engine(device())
.
Visualizations of the problem with rand:
Discussion:
One post mentions an article about the quality of the standard ones being "low" for their own quality requirements. And a followup post providing alternatives.
Why just the average is not good enough? And the histogram? Because the relation between the values is more complex than that. The tests should be aiming to detect patterns in various forms. E.g. you can get a perfect histogram by just generating the sequence 1, 2, 3, etc. See Randomness test.
The PCG authors also have a table with qualities that are allegedly making a PRNG better than others.
Cryptography
Rust
Reverse engineering
Text
Mustache and text templates
Articles on the topic of text templates
The truthy/falsey problem
The article above points out this problem with the "truthyness" in different languages:
Language | '' | 0 | "0" | {} |
---|---|---|---|---|
PHP |
False |
False |
False |
True |
Python |
False |
False |
True |
False |
JavaScript |
False |
False |
True |
True |
Ruby |
True |
True |
True |
True |
Lua |
True |
True |
True |
True |
This has popped up in issues and pull requests:
https://github.com/mustache/mustache/pull/260 https://github.com/mustache/mustache/issues/206 https://github.com/mustache/mustache/pull/210
In Rails, as a workaround, you can use presence if you want a blank string to be false:
template = <<-HTML {{#thing}}{{#presence}}Thing{{/presence}}{{/thing}} {{^thing}}Nothing{{/thing}} HTML Mustache.render(template, {}).strip # => "Nothing" Mustache.render(template, {thing: nil}).strip # => "Nothing" Mustache.render(template, {thing: ""}).strip # => "Nothing" (not both true and false) Mustache.render(template, {thing: true}).strip # => "Thing" Mustache.render(template, {thing: false}).strip # => "Nothing"
presence
is part of Rails, but hopefully that gives some people ideas about other ways to work around this problem in Ruby.