Posts

Showing posts from May, 2019

Move Semantics

In this post we are going to take a look at move semantics. Move semantics rely on the concept of rvalues, which were introduced in C++11. First we must make the distinction between lvalues and rvalues. lvalues are called as such because they have traditionally appeared on the left hand side of an assignment operator and designate an object (among other things). rvalues are called as such because they have traditionally appeared on the right hand side of an operator and typically designate temporary objects (possibly other things). How do we refer to such things in C++? Like so... X & // lvalue reference X & & // rvalue reference What are the uses of such things? One of the main ramifications of rvalue references is move semantics. What this allows us to do is create objects from temporary objects without having to make a deep copy. # include < iostream > # include < list > class BigVec { private : int m_size ; doub...

Static Objects

Static variables in C++ are initialised once and then exist for the lifetime of the programme. Once they have been initialised they can be referred to by using the variable name they were initialised with. In the following code we can see a simple example of the use of static variables. # include < iostream > # include < list > class Base { public : Base ( ) { } ; void foo ( ) ; } ; std :: list < Base * > & thing ( Base * bp ) { static std :: list < Base * > p ; if ( bp ) p . push_back ( bp ) ; return p ; } class Bar { public : Bar ( Base * b ) { thing ( b ) ; } } ; static Bar my_foo ( new Base ( ) ) ; int main ( ) { auto mods = thing ( nullptr ) ; std :: cout < < mods . size ( ) < < std :: endl ; // returns 1 return 0 ; } The first time the function 'thing' is called is via the 'Bar' constructor, in which the sta...