[HN Gopher] Constructors and evil initializers in C++
___________________________________________________________________
Constructors and evil initializers in C++
Author : todsacerdoti
Score : 11 points
Date : 2021-11-24 18:53 UTC (4 hours ago)
(HTM) web link (jmmv.dev)
(TXT) w3m dump (jmmv.dev)
| dabitude wrote:
| I work without exceptions, and the typical solution is to crash
| the whole program (using assert) if the parameter is invalid.
| This way you can preserve the invariant.
|
| To avoid crashing, the caller has to validate the parameters
| before calling the constructor, and handle the invalid parameters
| at this time rather than in the exception handler, but in the end
| it's the same.
| jmmv wrote:
| Crashing is fine if you are dealing with trusted input. But in
| the post, parameter validation was just an example. I've seen
| plenty of code using init methods to create network connections
| and the like -- and in those cases, you need proper error
| propagation.
| TheMonarchist wrote:
| The proper solution would be taking parameters that can't be
| invalid; it pushes validity check to the call site.
| OskarS wrote:
| I'm sorry, but the final version is FAR AND AWAY the worst
| version of all the code examples on the page. This tiny class in
| the stack-allocated version is lightweight, takes up very little
| space, has great cache locality and performs fantastically: all
| operations on it will probably compile down to one or two
| instructions touching memory almost certainly in cache.
|
| The heap-allocated version is so much worse! Not only do you have
| to pay for allocating and freeing it, every time you reference
| it, you're gonna have to chase a pointer. Imagine if you had 1000
| of these in a vector: the stack allocated ones would be right
| there next to each other, incredibly cache friendly. The heap-
| allocated ones are gonna cache miss constantly, and there's ZERO
| chance the loop is going to auto-vectorize. Show this to a data-
| oriented design person and watch their eyes start bleeding.
|
| And for what? So you can return null? Just return a std::optional
| from the factory method if you care so much (or boost::optional
| if you're on pre-C++17). Or use exceptions. Or just accept the
| fact that it might return the default value. All of those options
| are better than the final one. If you're choosing to program in
| C++, it means you should care about performance. If you don't
| care about performance for this kind of stuff, just use a higher-
| level language.
___________________________________________________________________
(page generated 2021-11-24 23:02 UTC)