DEV Community

loading...
Cover image for Intro to modern C++

Intro to modern C++

zigabrencic profile image Ziga Brencic Originally published at zigabrencic.com ใƒป5 min read

Cover image 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:

  • write your programs in English even if you don't have to. They become more readable.
  • split larger sections of code into files: ~300 lines max per file
  • don't use too much libraries per project
  • use descriptive variables not something like stRG2 or sss. The variable has to tell the reader descriptively what it represents. Good practice would be num_of_simulation_steps for example.

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:

  • use CLion editor (it's free for students and academics for non commercial use) and cmake build system
  • file that contains int main(){} should be named main.cpp that's usually good practice ๐Ÿ˜€
  • use descriptive names for variables and objects
  • don't do stuff globally, in 99% of the cases it's bad design
  • use STL (standard template library)
  • don't optimize your code for performance from the get go. Compiler is usually smarter then you in most cases :) Let it do it's job.
  • use STL libraries for example: #include<cmath> from STL instead of #include<math.h>
  • Don't use global name spaces using namespace std sure you write a bit more code but you keep the option open to introduce functions with same names
  • strive for code readability over performance. At the end what costs you the most is the time that coders spent on your code base.

If you find any bugs/mistakes shoot me a massage. Stay tuned for the upcoming articles. This is just the beginning of the series ๐Ÿ˜‰

Discussion (0)

pic
Editor guide