[Solved] dereference on new object when initiating new object


Yes but it does not mean dereference in this case. I’ll break up this line of code – tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI().

For the left hand side, how I’ve learnt to read is to start from the identifier and go right and when you reach the end, go back left. So we start at api then go right but there’s nothing (assuming we are only looking at the left hand side), so we head left. We see * and this means a pointer. Next we see tesseract::TessBaseAPI, which is the type of the pointer. Therefore, in words, api is a pointer to tesseract::TessBaseAPI. There are exceptions to this way of reading i.e. when there’s brackets or array but that’s the general idea.

For the right hand side, new means to allocate memory in the heap (as opposed to the compiler automatically allocating and deallocating memory for you in the stack) and thus, new tesseract::TessBaseAPI() means that you want to allocate enough memory in the heap for tesseract::TessBaseAPI object.

By combining the left and right hand sides, we get, in words, api is a pointer of type tesseract::TessBaseAPI that is currently pointing to the memory location that has been allocated in the heap.

If you’re confused whether * means a pointer or dereference, it’s a pointer when it’s a variable declaration or definition and dereference otherwise. This means that after your line tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(), whenever you call *api, it’s a dereference.

Edit:

Allocating memory on the heap means you’re responsible for it and the compiler will not help you to deallocate memory when you don’t need it anymore. The method to deallocate memory is by calling delete. If you don’t, you’ll get memory leak.

There is another method to allocate memory, which is malloc and the method to deallocate is by calling free. The difference between malloc and new is that malloc just allocates memory whereas new allocates memory and calls the constructor. DO NOT deallocate memory by calling free that you’ve allocated by using new and vice versa. If you use new, only use delete and if you use malloc, only use free.

If you think manually allocating/deallocating memory is troublesome, C++11 introduced something called smart pointers, which automatically allocates and deallocates memory for you. So for example, instead of the line tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(), you can have

#include memory
auto ptr = std::make_unique<tesseract::TessBaseAPI>(); //ptr acts like a normal pointer

When you don’t need it anymore, just leave it as it is and it’ll be deallocated when it exits its scope. This is a pretty neat way since there’s no explicit new and delete so you don’t have to worry about memory leak. Of course, there’s some extra overhead as compared to using raw pointers so it’s a trade-off.

1

solved dereference on new object when initiating new object