1

Does making an unnecessary pointer use noticeably more resources rather than just using an object itself? For example:

Enemy e1;
e1.attack();

vs

Enemy e1;
Enemy *ptr = &e1;
ptr->attack();

Does creating and using the pointer use lots of resource? Or does creating a pointer not use that much, regardless of it being a class pointer or say an integer pointer?

torhara
  • 101
  • 6
  • 1
    Why would you write three lines of code where two would do? That alone uses significant resources: your time. – user207421 Sep 03 '19 at 04:02
  • 1
    In this particular example, the compiler is likely to produce the same machine code for both code snippets – Remy Lebeau Sep 03 '19 at 05:10
  • One pointer takes 4 or 8 bytes of memory based on the processor type, but they are meant to be used for dynamic memory allocation, so for variable defined in the stack you can either use the variable itself or its reference for passing without copying that variable. – muaz Sep 03 '19 at 09:33
  • @user207421 -- it's an **example** to illustrate the question. – Pete Becker Sep 03 '19 at 12:48
  • @muaz -- while pointers are most commonly used to manage dynamic allocations, that is not all they are used for. Passing by reference is not always a replacement for passing a pointer. – Pete Becker Sep 03 '19 at 12:49

2 Answers2

4

As you stated that the use of the pointer is unnecessary, I guess you have a use-case where the use would not actually be unnecessary but provides some benefit.

You can use a simple example to verify that most compilers (I tested GCC 5.1, 9.0 and clang 8.0, all x64) produce the exact same code (hence no difference in resource usage) when accessing the object: - directly - via pointer - via reference

#include <iostream>
using namespace std;

class Enemy
{
    public:
    Enemy() {}
    void attack() 
    {
        cout << "attack";
    }
};

#define VERSION 1

int main(int argc, char* argv[]) {
    Enemy e;
#if VERSION == 1
    e.attack();
#elif VERSION == 2
    Enemy& e2 = e;
    e2.attack();
#else
    Enemy* e3 = &e;
    e3->attack();
#endif
}

You can easily try different compilers and options with Godbold (includes example above)

IIRistoII
  • 320
  • 1
  • 7
flba
  • 379
  • 1
  • 11
1

Pointer memory occupation have a fixed size equivalent to your memory's address size, e.g. 64 bits for 64 bit machines, see this question. It uses that amount of memory independent of size/type of the value it points to, be it a primitive or a class.

That said, decaying a value to it's pointer is error prone, as you can nullify that pointer and suffer from invalid memory access or undefined behavior. If you can avoid it, why not?

ranieri
  • 2,030
  • 2
  • 21
  • 39