Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax I don't understand

Tags:

c++

syntax

I've found a C++ code that has this syntax:

void MyClass::method()
{
    beginResetModel();

    {
        // Various stuff
    }

    endResetModel();
}

I've no idea why there are { } after a line ending with ; but it seems there is no problem to make it compile and run. Is it possible this as something to do with the fact that the code may be asynchronous (I'm not sure yet)? Or maybe the { } are only here to delimit a part of the code and don't really make a difference but honestly I doubt this. I don't know, does someone has any clue what this syntax mean ?

More info: There is no other reference to beginResetModel, resetModel or ResetModel in the whole project (searched with grep). Btw the project is a Qt one. Maybe it's another Qt-related macro I haven't heard of.

like image 829
MoaMoaK Avatar asked Dec 10 '22 10:12

MoaMoaK


2 Answers

Using {} will create a new scope. In your case, any variable created in those braces will cease to exist at the } in the end.

like image 79
informaticienzero Avatar answered Dec 27 '22 14:12

informaticienzero


   beginResetModel();
   {
       // Various stuff
   }
   endResetModel()

The open and close braces in your code are a very important feature in C++, as they delimit a new scope. You can appreciate the power of this in combination with another powerful language feature: destructors.

So, suppose that inside those braces you have code that creates various objects, like graphics models, or whatever.

Assuming that these objects are instances of classes that allocate resources (e.g. textures on the video card), and those classes have destructors that release the allocated resources, you are guaranteed that, at the }, these destructors are automatically invoked.

In this way, all the allocated resources are automatically released, before the code outside the closing curly brace, e.g. before the call to endResetModel() in your sample.

This automatic and deterministic resource management is a key powerful feature of C++.


Now, suppose that you remove the curly braces, and your method looks like this:

void MyClass::method()
{
    beginResetModel();

    // {
        // Various stuff
    // }

    endResetModel();
}

Now, all the objects created in the Various stuff section of code will be destroyed before the } that terminates the MyClass::method(), but after the call to endResetModel().

So, in this case, you end up with the endResetModel() call, followed by other release code that runs after it. This may cause bugs. On the other hand, the curly braces that define a new scope enclosed in begin/endResetModel() do guarantee that all the objects created inside this scope are destroyed before endResetModel() is invoked.

like image 37
Mr.C64 Avatar answered Dec 27 '22 13:12

Mr.C64