PentiumPro200
PentiumPro200

Reputation: 631

When is a stack object within a function call constructed?

Say I have a simple function:

void foo(int val) {
    if(val == 0) {
       return;
    }
    else {
      stringstream ss;
      ss << "Hello World" << endl << ends;
      cout << ss.str();
   }
}

If I call the function with val == 0, does the stringstream object ss ever get constructed? I suspect no, but just want to confirm.

Upvotes: 4

Views: 98

Answers (2)

ppsz
ppsz

Reputation: 342

Since the program won't run to this point, this stringstream won't be constructed.

Upvotes: 1

Aracthor
Aracthor

Reputation: 5917

This is precisely how scopes in C/C++ are useful: to not construct objects that you don't want to be constructed.

Here, your stringstream object shall only be constructed if you penetrate in its scope, defined by else curly brackets.

So no, your object won't be constructed if val == 0.

Upvotes: 4

Related Questions