Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a pointer or a stack variable

Tags:

c++

c++11

Assume we have the following case:

  • If it is morning mood is good otherwise mood is bad
  • Print the mood

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

like image 595
Humam Helfawi Avatar asked Mar 24 '26 03:03

Humam Helfawi


2 Answers

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") };
like image 67
NathanOliver Avatar answered Mar 26 '26 16:03

NathanOliver


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);
like image 22
Jens Avatar answered Mar 26 '26 15:03

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!