4

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
PentiumPro200
  • 641
  • 7
  • 23
  • 1
    No, `ss` does not get constructed as it is in a different scope that is never entered. – callyalater Mar 03 '16 at 23:16
  • 3
    It's easy to tell: just put a class you wrote instead of `stringstream` (extend `stringstream` for example) and let its constructor and destructor output some messages. You can find out this way the exact moment when each object is created and destructed. – axiac Mar 03 '16 at 23:19
  • @axiac, that's a clever trick. I'll try that next time I want to see if an object gets constructed. – PentiumPro200 Mar 03 '16 at 23:26
  • @PentiumPro200 _"that's a clever trick"_ Well, the simplest approaches are often the most clever ones. – πάντα ῥεῖ Mar 03 '16 at 23:31

2 Answers2

4

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.

Aracthor
  • 5,757
  • 6
  • 31
  • 59
1

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

ppsz
  • 342
  • 1
  • 10