c++: when to use pointers?

后端 未结 14 1697
无人共我
无人共我 2020-12-12 22:48

After reading some tutorials I came to the conclusion that one should always use pointers for objects. But I have also seen a few exceptions while reading some QT tutorials

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 23:44

    It's not clear to me if your question is ptr-to-obj vs stack-based-obj or ptr-to-obj vs reference-to-obj. There are also uses that don't fall into either category.

    Regarding vs stack, that seems to already be covered above. Several reasons, most obvious is lifetime of object.

    Regarding vs references, always strive to use references, but there are things you can do only with ptrs, for example (there are many uses):

    • walking through elements in an array (e.g., marching over a standard array[])
    • when a called function allocates something & returns it via a ptr

    Most importantly, pointers (and references, as opposed to automatic/stack-based & static objects) support polymorphism. A pointer to a base class may actually point to a derived class. This is fundamental to the OO behavior supported in C++.

提交回复
热议问题