Common C++ traps

Revision en2, by InRainbows, 2025-04-21 20:26:08

Hello everyone! Today I want to write about common C++ mistakes that may seem correct while writing code, but are actually wrong upon deeper inspection. There are only few right now because finding one requires deep experience in coding and often quite specific to certain problems. If you have any suggestions, I can add them to this blog.

size_t type is unsigned

When you get the size of some container it returns unsigned integer, not regular integer. It may lead to mistakes like this:

for (int i = 0; i < Ar.size() - 3; i++)

If size of Ar is less than 3, Ar.size() - 3 won't be some negative integer, it will be large positive integer because of how unsigned integers work.

Common mistake with pointers

Let's say you wanted to create a vector of multiple pointers, and you wrote it like this:

vector<node*> T(N, new node());

This might seem correct but it isn't. Keep in mind that all those pointers will point into one node, not N nodes, so if you change one, it will affect all of them. Instead, you have to add them one by one:

vector<node*> T;
for (int i = 0; i < N; i++) T.push_back(new node());
Tags tips, c++

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English InRainbows 2025-04-22 11:28:30 534 Tiny change: 'o integer like `(int)t.s' -> 'o integer using `(int)t.s'
en2 English InRainbows 2025-04-21 20:26:08 130
en1 English InRainbows 2025-04-21 20:17:54 1109 Initial revision (published)