Tuesday, March 7, 2017

C++11 features in Opendtect

OpendTect is since a couple of weeks using standard C++11 compliant compilers on all platforms, and we are therefore ready to start using some of the features in the updated language, while we will refrain from others. Here are the features that can be used in OpendTect:

Class variable assignment at declaration

C++11 allows assignment of variables directly in the class declaration:

mExpClass(Basic) A
{
    int b = 1;
};

If there are no further intelligence in the constructor, the constructor does not need to be defined or implemented as the assignment of the variables are done automatically. If you want to have it at a different value in a specific constructor, you can override the assignment in the constructor:

A::A()
    : b( 2 )
{}

Using this functionality, we can remove macros that are common with multiple constructors, where the sole use of the macro is to assign variables to default values.

Constructor delegation

You can now let one constructor call another constructor:


A::A( const char* str )
    : is_same_( strcmp(str,"mystring)==0 )
{}


A::A( const OD::String& str )
    : A( str.str() )
{}
    
Again, this can be useful as you can put all intelligence in one constructor, and have the other constructors call it.

Explicitly not creating operators or constructors

Every now and then, there are classes where you explicitly do not want the copy constructor or assignment operator. When the compiler wants these, it will normally try to create them automatically, which may lead to unwanted conversions between types. You can now explicitly forbid the compiler to do this by declaring a member "= delete":

mExpClass(Basic) A
{
public:
        A();
        A(const A&)         = delete;
    A&  operator=(const A&) = delete;
};

If you attempt to use one of these functions, the compiler will stop you at compile time.

R-Value references

C++ 11 allows references to R-Values using a double &&. If you know what you are doing, you may use these in constructors and assignment operators to create more effective assignments and constructors.


No comments:

Post a Comment