Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different methods to use a class/struct - C++

Tags:

c++

methods

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?

like image 261
Navaneeth K N Avatar asked May 06 '26 12:05

Navaneeth K N


1 Answers

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.

like image 90
Johannes Schaub - litb Avatar answered May 08 '26 01:05

Johannes Schaub - litb