When explicitly initializing std::optional's, should I use nullopt? [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
An std::optional<T> can be initialized to the disengaged state like so:
std::optional<int> oi { nullopt };
but also like so:
std::optional<int> oi { };
and similarly for assignment (oi = {} or oi = nullopt).
Other than personal preference / sense of aesthetics, is there a difference between these which should make me prefer one over the other? Or does it not matter at all?
Note: I'm asking about cases where I want to explicitly initialize the optional, rather than default-initialize it (e.g. for emphasis).

It does not matter at all. Choose whatever makes your colleagues understand your code better.

They both have the same effect - I would prefer the simplest form (KISS), but it is subjective, pick one and be consistent. You may also wish to be consistent with how you treat other objects in your code, do you normally rely on default initialization (e.g. int i{} vs int i{0})?
Personally when I see redundant code, like initalizing an object to its default value explicitly, it does reduce my confidence in the author by a slight margin - does the author really understand what he is doing and trying to be extra safe / explicit / readable, or was he simply too lazy to read the documentation? It makes me wonder, does the author understand what happens when he writes std::vector<std::optional> v(n), or more complex examples? If this is a documented decision, in a coding style, then all is fine, I can understand the need to improve readability.

Related

Should I favor direct list initialization over copy initialization as a general rule of thumb? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Is it recommended in C++ 20 to always favor direct-list-initialization over copy initialization or even direct initialization as a general rule of thumb? As an old C++98 programmer coming back to C++ after 15 years it still feels natural to use auto i = 5 instead of auto i {5}. I want to make sure the "new" way really is the new default before "burning in" the new way into my coding guides.
I suppose post modern C++ enables you to express "intent" instead of "operation". In that sense auto i {5}; would state you allow the compiler to choose the type and that you only care about 'i' being initialised, not caring how that happens? But if your intent is to initialise in some specific way you have chosen to be "the best" in some sense, then choose the initialisation you think comes closest to that way :)

Are there potential performance penalties for `auto o = SomeType(args)` instead of `SomeType o(args)`? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm a great fan of auto and prefer writing auto o = SomeType(args).
It almost always results in calling a constructor only.
#NathanOliver showed that -fno-elide-constructors is capable of turning off copy elision and resulting in a call to a constructor and an assignment operator.
Are there real-world cons of writing auto o = SomeType(args)?
Sort of, but no.
Back in the day, and by that I mean pre-C++17, this would be a stylish kind of copy-initialisation. Now by stylish I mean "let's use auto for the heck of it", and by copy-initialisation I mean "this is going to use the copy constructor" (or the move constructor, if you have one).
In practice, you were always likely to observe (or, lol, not observe) a distinct lack of copy construction (or of move construction), thanks to a beautiful thing called return value optimisation. Ish.
And, since C++17, this is actually guaranteed to produce neither a copy nor a move, thanks to guaranteed elision.
However it's still kind of silly. So there you go.
Honestly, just declare your variable normally:
SomeType o(args);
Your readers, or at least most of them, will thank you.
Bonus (negative) points for auto main() -> int { /* ... */ } and yes there are actually people here who insist on that!

Style preference in setters: Class::member = value or this->member = value? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
This seems like a really simple question, but I've been unable to find any opinions on it. When writing setters in C++, what is the difference between
void ClassName::set_member( type value ) {
ClassName::member = value;
}
and
void ClassName::set_member( type value ) {
this->member = value;
}
CLion generates the first version, so I suspect it has some advantage, but I don't see what that would be.
The difference is purely syntactic. Both versions have exactly the same effect. It doesn’t even matter whether member is static or non-static. Only from inside a static member function you cannot use the this-> version because there is no object and thus no this.
Because it feels really weird it bears repeating: Even if member is a static member variable this->member = value; is valid and does the right thing.
As for preferring one style over the other: like all stylistic choices that’s highly subjective. A clear answer isn’t really possible. But there are indictators of what the C++ community prefers in general. You might look at:
open source C++ code on GitHub etc., or your standard library implementation
code snippets on presentation slides from major conferences like CppCon, Meeting C++, C++ Now etc.
major C++ books, e.g. Stroustroup’s The C++ Programming Language or Scott Meyers’ Effective C++ series
Considering all that I’m confident to say that the prevalent style is none of your two, but:
member = value;
On a purely personal note: For non-static members the ClassName:: version feels unfamiliar to an extent that I would call it out in a code review. this-> usually makes me wonder “Was this written by a Java programmer?”, but overall – especially if it’s used consistently – it’s an ok style, although unusual; and in some special template metaprogramming cicumstances it’s even mandatory.

static __forceinline or __forceinline static [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Good morning, this always made me wonder (even tho it doesn't really matter) but which one is the correct way? Or is there none and both ways are fine?
static __forceinline T some_func ( )
or
__forceinline static T some_func ( )
It is important to order modifiers alphabetically, except if you are writing code on the solstice or equinox (during which it angers the sun microsystems god).
Other than that, use whatever order you wish, so long as you are willing to live with the consequences.
Which are none.
As you said yourself, both are legal and their results are identical so it comes down on personal preference.
For what it's worth in most codebases I've worked compiler specific keywords were always used before any standard C++ keywords which makes your 2nd snippet more common.
However as always with code style, just pick one you like most and be consistent. Consistency is what's important.

Is it considered bad programming practice to have a large number of overloaded class constructors? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm making a calendar application in c++ and I'm making a great number of overloaded constructors for the appointment class depending on the information provided(e.g. if i have a start time for the event but no end time, and a location, but no attached contacts)
class Appointment {
public:
//overloaded Constructors
Appointment();
Appointment(Date);
Appointment(Date,Date);
Appointment(Date,Date,std::string);
Appointment(Date,Date,std::string,std::string);
Appointment(Date,Date,std::string,std::string,Contact);
etc. etc. Is there a better way to do this?
You could either:
Create the object (a valid one) and set its properties afterwards via interface setters (since it seems an object can have a variable number of properties this seems like a good choice)
Use default parameters, e.g.
Appointment(Date=getDefaultDate(),
Date=getDefaultDate(),
std::string=getDefaultString(),
std::string=getDefaultString(),
Contact=getDefaultContact());
It really boils down to how you prefer to handle and initialize your objects.
An important sidenote: in large production codebases default parameters is a C++ feature often frowned upon because it might hinder readability and/or render debugging more difficult in particular scenarios (especially when something unwanted goes on and you didn't consider a default parameter being chosen, default parameters are specified on the declaration and that might also "hides" a potential problem from the developers)
This is totally unnecessary. As pointed out Macro A , you can default construct the object and afterwards you can use setters for them.
One more thing when designing a software you should keep in mind the rule of complete and minimal i.e you should provide all facilities in a class avoiding duplication/redundancy.