C++ Objects: When should I use pointer or reference

前端 未结 9 1446
情话喂你
情话喂你 2020-12-03 08:45

I can use an object as pointer to it, or its reference. I understand that the difference is that pointers have to be deleted manually, and references remain until they are o

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 09:14

    Here's another answer (perhaps I should've edited the first one, but since it has a different focus, I thought it would be OK to have them separate).

    When you create a pointer with new, the memory for it is reserved and it persists until you call delete on it - but the identifier's life span is still limited to the code block's end. If you create objects in a function and append them to an external list, the objects may remain safely in the memory after the function returns and you can still reference them without the identifier.

    Here's a (simplified) example from Umbra, a C++ framework I'm developing. There's a list of modules (pointers to objects) stored in the engine. The engine can append an object to that list:

    void UmbraEngine::addModule (UmbraModule * module) {
        modules.push(module);
        module->id = modules.size() - 1;
    }
    

    Retrieve one:

    UmbraModule * UmbraEngine::getModule (int id) {
        for (UmbraModule **it=modules.begin(); it != modules.end(); it++) {
            if ((*it)->id == id) return *it;
        }
    }
    

    Now, I can add and get modules without ever knowing their identifiers:

    int main() {
        UmbraEngine e;
        for (int i = 0; i < 10; i++) {
            e.addModule(new UmbraModule());
        }
        UmbraModule * m = e.getModule(5); //OK
        cout << m << endl; //"0x127f10" or whatever
        for (int j = 0; k < 10; j++) {
            UmbraModule mm; //not a pointer
            e.addModule(&mm);
        }
        m = e.getModule(15);
        cout << m << endl; //{null}
    }
    

    The modules list persists throughout the entire duration of the program, I don't need to care about the modules' life span if they're instantiated with new :). So that's basically it - with pointers, you can have long-lived objects that don't ever need an identifier (or a name, if you will) in order to reference them :).

    Another nice, but very simple example is this:

    void getVal (int * a) {
        *a = 10;
    }
    int main() {
        int b;
        getVal(&b);
        return b;
    }
    

提交回复
热议问题