Tips and tricks for c++ pointers and operators

If you really want to get the best performance from your c++ coding adventures, you’re gonna have to really get deep into the low-level experience. That means learning how to use pointers and directly accessing memory and data, which is always risky, but with care and proper practices, it shouldn’t even make you flinch. So here are some tips on how to master even c++ pointers and operators.

Usually when you’re accessing a pointer to a member of a class or object, you can do so in c++ like this:

//accessing member of object 10 in the someObject array/list
someObject[10].member

The [] operator is no different than this:

int * someObject;
int * someObjectMemberPtr = &someObject + sizeof(int) * 10;
SomeObject someObject = *someObjectMemberPtr;
someObject.member = 123;

Assume someObject is an array of int data type. It’s an integer data type that’s 32 bits aka 4 bytes. When you’re using [] brackets operator, you’re accessing the pointer to the memory location of the first member of that indexed item in the array. So someObjectMemberPtr is pointing to the address of the 10th item in the someObject array.

Then we DEREFERENCE the someObjectMemberPtr address with the * asterisk to return the object by reference, or what we would consider the “normal” object. And from there, we can access the object member and assign a new value to it or use the value.

To dereference a pointer, you can do so like this as well:

int * valuePtr;
int value = **valuePtr;

And to get the pointer from an object, you can do so like this:

int * valuePtr;
int value = 123;
valuePtr = &value;

You can get a pointer to the address of an object using the & ampersand special character. By default, it is usually assumed all objects are accessed by reference anyway and the ampersand is implicitly used. But if you explicitly use an ampersand on your object, you won’t be able to access the member anymore. It’s all a matter of how the interpreter/compiler handles the syntax.

Also, pay attention to how you access members too.

someObject->member = 123

When an object uses the -> pseudo arrow accessor, it means the object is being accessed by pointer.

someObject.member = 123

When an object uses the . period accessor, it is accessing it dereferenced. I think the difference is the number of steps internally it takes to get you access to the data. Using the pseudo arrow accessor might actually be faster because it’s direct access. But neither one gives you write-protection.

In Qt c++, you can use the .at() accessor for read-only access, which is smarter practice if you’re dealing with lots of data and don’t want to accidentally overwrite anything.

So if you’re ever using a version of c++ that doesn’t come with fancy convenience classes like Qt’s powerful QList or QVector classes, you have to do it in old-fashioned pure c++ or c style and access things directly. It can get messy or scary, but it’s quite powerful in the right hands.