Home Blog Newsletters About

Intro to modern C++

Source

I turn to C++ when I have to do some sort of massive data crunching. In any other case I turn to python since I can write numeric code in it faster. But there are cases where C++ is the only way to get out alive. We’ll mention some advance concepts here but mostly to make you as a novice aware that they exist. Because you always don’t know what you still don’t know and I’ll try to bridge this gap a bit.

C++ not the C way

In natural sciences for some reason people practice and teach the young the C++ the C way. Maybe they are stuck in the past or were just lazy to learn the cool features of modern C++ (C++ 17). But this C is C++ mantra is producing an army of coders that are not leveraging modern tools.

I keep seeing code that uses double x[100]; for arrays instead of std::vector<double> x(100);. Or even worse: double *x = new double[100];. Hack when I started coding I was doing the same thing. Then someone told me. Hey there’s this thing cold STL (C++ Standard Template Library) that has vectors that are smart. If you try to access an element that doesn’t exist it will raise a warning. Cool that’s worth exploring.

If you use std::vector<double> instead of a double array you have some pretty cool features at your disposal. You can enlarge the vector as the program gets executed, resize it, clean it up, … To access elements you can use x.at(i) instead of x[i] sure the [i] is faster but it doesn’t check like .at(i) if you are accessing elements that are not in the vector.

IDE is your friend

Use something like CLion it’s the best Interactive Development Environment out there. It will tell you what you screwed up, remind you that you’re maybe making some redundant copies of data, … For the geeks. You can use vim mode in it ;)

Don’t use raw * pointers. Ever !!

But they are fast right. Yes sure raw pointers are the most efficient way to blow your head off :) General rule of thumb is that you don’t use pointers at all. OK except for the reference & which you use when you don’t want unnecessary copying. For example when passing data to a function:

void my_calculator(const std::vector<double> &x){
// implementation
}

const will make sure that the function can’t modify x that you passed in. If you wouldn’t pass in &x but just x the data would be copied for no reason.

If you really have to use pointers then smart pointers. std::shared_ptr or std::unique_ptr are the answer. Sure there might be some small percentage of cases where the library you are using forces you to use raw pointers (BTW that’s bad library design). In that case keep in mind that smart pointer is just a smart envelope around the raw pointer so you can always get the raw pointer ‘out’. Example of packaging an arbitrary C++ object into a smart pointer would be:

std::shared_ptr variable_name = std::make_shared<Object>();

Instead of the raw way that you shouldn’t use ever:

double *x = new double [100];

Now why the hack is something like double * so dangerous? Well if you delete the raw pointer to your data you will have pretty hard time getting back to it and cleaning it up. So before you realise your RAM is full and your PC can’t perform any new calculations. In fancy words you cause a memory leak. By using smart pointers the smart pointers implementation sort of prevents you from doing that.

Code readability over performance

I always recommend that you write code with readability in mind first. So other people (yes your future self in 2 years included) can understand, read and use the code afterwards. I propose that you:

There a thousand more guidelines but in general the above should give you the basis. For more you can check code style guides from google or someone else. But be careful at the end of the day you want to write code that produces good results so strike for healthy balance on spending time writing clean code and one that works. Your code readability will improve as you gain programming experience. In a sense programming is learning tricks and the person with most tricks is the ‘best coder’.

Don’t go down the optimisation rabbit hole

Don’t try to optimise the code for performance from the start. In most of cases that’s usually a bad idea. Simply because before you write your whole program you don’t know what the slow parts are. Maybe some function is slow but you don’t really care because you run it once in your entire program. On the other had you might be executing specific line of code millions of times per program execution. That’s the part that should be optimised. So general rule of thumb. Write your program. Then figure out where most of the program execution time is spent and optimise that part.

Key takeaways

So what you should take from here:

If you find any bugs/mistakes shoot me a massage at: ziga dot brencic at gmail dot com.

Get the weekly experiment newsletter to your inbox:

with