Assume we have the following case:
it could be written as:
std::string mode; //this cost us calling the constructor of std::string
if(time==Morning){ // a real code should be here
mood="Good"//re assign the string
}
else{
mood="bad"//re assign the string
}
std::cout << mood;
assuming it is not std::string, it is a very big object. Isn't it too luxury to declare "mode" and call the constructor for no reason! Is using the raw pointer a solution? what is the best practice here? thanks
You could use the ternary operator to initialize the string.
std::string mode = (time == Morning ? "Good" : "Bad")
As MSalters pointed out in the comments this is actually still two constructions(constructor + copy) but it should get optimized by the compiler. You can directly initialize the string with
std::string mode { (time == Morning ? "Good" : "Bad") };
I would consider putting the logic into a separate function. This helps to keep functions small and simple.
std::string moodAtTime(Time time)
{
if(time==Morning)
{ // a real code should be here
return "Good";
}
else
{
return "bad";
}
}
std::string mood = moodAtTime(t);
This reduces function length and splits the code into small units performing simple questions.
If it is only for initialization, you can use a lambda to do it without the named function:
std::string mood = [](Time t)
{
if(t==Morning)
{
return "Good";
}
else
{
return "bad";
}
}(now);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With