I am new to C++. I got accustomed with pointer and memory allocation, but there is still some question in my mind. When we prefer references rather than pointers, is there any kind of technical distinction? Another question in my head is that is there any relationship between pointers and program performance. Let me explain, I knew that using pointers means allocating heap, but using them could potentially improve my program's performance?
Asked
Active
Viewed 48 times
0
-
The differences between pointers and references are mostly semantic and handled by the compiler at compile-time. They tend to be implemented similarly. And pointer could actually *decrease* performance, if we consider them as indirect access to objects, where two memory accesses are needed to get a value from an object or to all a member function: One memory access for the pointer, and one for the object. – Some programmer dude May 12 '20 at 20:01
-
With that said, in modern C++ there's often little need to use pointers outside of polymorphism. Concentrate on writing good, readable and maintainable code, that works and works well. Then if there are some efficiency requirements, build an optimized release version, and *measure* the performance, and *profile* the program to find the top two (or maybe three) bottlenecks, and concentrate on those only, and write plenty of documentation and comments about any manual optimizations of the code you make. Repeat until it's "good enough", but no further. – Some programmer dude May 12 '20 at 20:04
-
3"I knew that using pointers means allocating heap" thats a common misunderstanding, it is wrong. You can use pointers everywehre without a single dynamic memory allocation. Also the reverse isnt quite true. Standard containers manage dynamically allocated memory for you in a way that you never have to deal with a pointer. And latest since C++11 you shouldnt deal with raw owning pointers in any case – 463035818_is_not_an_ai May 12 '20 at 20:10
1 Answers
1
References and pointer do different things. References refer to existing variables, where as pointers are arbitrary addresses.
Here is a great write up on when to use each.
The question of performance improvements doesn't really make sense. Using the heap is necessary for a wide variety of reasons, it wasn't created for performance.

robinsax
- 1,195
- 5
- 9