tags:

views:

338

answers:

4
struct Foo
{
    void SayHello()
    {
     std::cout << "Hi, I am Foo";
    }
};

I have the above given struct. I have seen a usage like this in one of our code base.

Foo foo;
{
     foo.SayHello();
}

IMO, It does same like

Foo foo;
foo.SayHello();

Or is there any advantage/difference for the first method?

Any thoughts?

A: 

Did you by any chance mean that your first option is

{
  Foo foo;
  foo.SayHello();
}

That would make more sense because then the foo object is created, used, and destroyed within the smaller scope of the curly braces that wrap it. That is a common practice that aims to reduce the lifetime of transient things. Often, these sub-blocks can be refactored into separate functions.

Uri
+4  A: 

In that particular case, it looks quite strange and like a candidate for review. Can be useful in other cases:

Foo foo;
{
    ReturnValue v = foo.SayHello();
    Send(v);
}
...

Where it would limit the scope of v. One common use is to make the objects in it destroy earlier. Classes that do special stuff in their constructor and destructor can then be used inside the braces:

Foo foo;
{
    MutexLocker locker(sendMutex);
    ReturnValue v = foo.SayHello();
    Send(v);
}
...

The lock for the send-queue would be held while sending v in that example, and be released when the locker is destroyed at the closing brace.

Johannes Schaub - litb
That makes perfect sense. Thanks litb.
Appu
A: 

Identical as written (as far as I can tell).

As other people have said, that construct is usually used to limit scope of something, but in your example, there's no difference.

Nick
+4  A: 

There's no difference in the two examples. The following, however, would create and destroy the foo object within the scope of the braces:

{
    Foo foo;
    foo.SayHello();
}

This is useful for objects that follow the RAII idiom.