What is the most astounding C++ syntax construct?

Joined
Dec 21, 2022
Messages
28
Reaction score
4
C++ is a great language and for me personal the greatest programming language so far.

But there are also constructs possible which may look strange or really complicated.

Do you know some?

I wanna share a strange looking but sometimes very useful example:


C++:
// imagine having also some struct/class X, Y and Z...
class Foo
{
private:
    // some member mMember1 and mMember2 here...
public:
    Foo( X x, Y y, Z z ) // Constructor
    try : mMember1( x )  // A functional try block around the member initilizer list ...
        , mMember2( y, z )
    {
    } catch( ... ) {     // ... and the complete constructor body ...
        /* insert useful
        code here */
    }                    // ...  catching all execptions thrown from there.
};

There you see a Functional Try Block.
This is useful if in the middle of the member initialization an exception is thrown and the half created class instance need to do some clean up. There is one special behavior in this construct. Do you know which?

The catch block will always re-throw the exception automatically because the class instance was not finally created and stays broken.

One complete example:
C++:
class Foo
{
    std::string mStr;
public:
    // Constructor
    explicit Foo( std::string const & s, size_t pos )
    // # 4: Function try block. The try block includes the initializer list!
    try : mStr( s, pos )
    {
        puts( "Foo constructor - normal block." );
    } catch( ... ) {
        // here can only cleanup already initialized/allocated stuff, which must be clean up manually.
        // Constructed members are destructed already.
        // the class instance itself stays broken. this catch block will auto re-throw the exception always!
        puts( "Foo constructor - catch block!." );
    }
};
 
try {
    std::string s = "test";
    Foo foo1( s, 2 );  // not throw
    Foo foo2( s, 10 ); // will throw std::out_of_range
} catch( ... ) {
}

This is one example from my Christmas Special Blog Post:
TOP 5 most astounding C++20 syntax.

The complete top 5 you can read here: TOP 5 most astounding C++20 syntax

Do you know other awesome syntax constructs?

Cheers!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top