What's good in standard C++11 ?

24 views
Skip to first unread message

Dilawar Singh

unread,
Jul 4, 2016, 7:42:06 AM7/4/16
to wncc_iitb
Many things! And it has increased the size of already humongous C++. Whatever you can do with new c++11 features, you can most probably do without them; but many things have been cleaned up and/or requires less typing. C++ is a great language, albeit an ugly one, for system programming, simulations and embedded systems (not to mention to implement other languages). This make it extremely relevant to electrical engineers who often works at the interface of computer science with their discipline.

Heavy user of C++ should consult Scott Meyer's "Effective Modern C++" for much more comprehensive suggestions.

In any case, following are extremely useful features to start with. I am listing features which a student can easily use in his/her assignment/projects, assuming that you use C++ classes and STL (probably templated class/functions one as well).

Disclaimer: the snippets are not tested. They are here for demo purpose.

Uniform initialization syntax

foo_type myVar { ka, kha, ga }; or
foo_type myVar = { ka, kha, ga };

e.g.
vector<int> myInts{1, 2, 3};
list<float> myFloat {1.0, 1, 3e-12 };
vector<

Smart Pointers

They wrap the raw pointer and manage the resources. In short if you use smart pointers i.e. `unique_ptr`, `shared_ptr`, `weak_ptr` etc., you never have to use `delete` keyword. Most likely, you don't have to use `weak_ptr` ever unless you are maintaining a high performance library.

Type related especially `auto`

Usage of keyword `auto` for type inference and range based loop. A combination of both can reduce the for loop:

Old style

vector<int> myV;
// push into vector
for( vector<int>::const_iterator it = myV.begin(); it != myV.end(); it++ )
{
    // do something with *it
}


c++11 style


vector<int> myV;
// push into vector
for( auto& it : myV )
{
    // do something with *it
}

Other two useful items are `decltype` and `constexpr`. Former is useful in reducing the typing; later adds type safety.

Lambda and other functional thingies

You might have used them in python e.g. `lambda x: math.sin(x * math.pi / 360 )`. C++11 have a great native support for functional thingies. Boost::bind, boost::lambda users will definitely love this.


Others
  • Prefer `emplace_back` to `push_back` on std::vector. (why? Read about move semantic and if you think you can explain it in simple language, do post on the group. I am still struggling to grasp it.).
  • std::async is new keyword and much cleaner and better than std::thread.
  • Regular expressions are in STL. Though I still prefer boost::regex or pcre.h over it.
  • std::array is an enhancement of old style C array. Most if not all <algorithm> works on them as well.
  • Great support for random numbers/distributions.

--
Dilawar
NCBS Bangalore
Reply all
Reply to author
Forward
0 new messages