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?
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.
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