Why should I use a pointer rather than the object itself?

后端 未结 22 1664
予麋鹿
予麋鹿 2020-11-21 23:26

I\'m coming from a Java background and have started working with objects in C++. But one thing that occurred to me is that people often use pointers to objects rather than t

22条回答
  •  别跟我提以往
    2020-11-21 23:49

    There are many use cases for pointers.

    Polymorphic behavior. For polymorphic types, pointers (or references) are used to avoid slicing:

    class Base { ... };
    class Derived : public Base { ... };
    
    void fun(Base b) { ... }
    void gun(Base* b) { ... }
    void hun(Base& b) { ... }
    
    Derived d;
    fun(d);    // oops, all Derived parts silently "sliced" off
    gun(&d);   // OK, a Derived object IS-A Base object
    hun(d);    // also OK, reference also doesn't slice
    

    Reference semantics and avoiding copying. For non-polymorphic types, a pointer (or a reference) will avoid copying a potentially expensive object

    Base b;
    fun(b);  // copies b, potentially expensive 
    gun(&b); // takes a pointer to b, no copying
    hun(b);  // regular syntax, behaves as a pointer
    

    Note that C++11 has move semantics that can avoid many copies of expensive objects into function argument and as return values. But using a pointer will definitely avoid those and will allow multiple pointers on the same object (whereas an object can only be moved from once).

    Resource acquisition. Creating a pointer to a resource using the new operator is an anti-pattern in modern C++. Use a special resource class (one of the Standard containers) or a smart pointer (std::unique_ptr<> or std::shared_ptr<>). Consider:

    {
        auto b = new Base;
        ...       // oops, if an exception is thrown, destructor not called!
        delete b;
    }
    

    vs.

    {
        auto b = std::make_unique();
        ...       // OK, now exception safe
    }
    

    A raw pointer should only be used as a "view" and not in any way involved in ownership, be it through direct creation or implicitly through return values. See also this Q&A from the C++ FAQ.

    More fine-grained life-time control Every time a shared pointer is being copied (e.g. as a function argument) the resource it points to is being kept alive. Regular objects (not created by new, either directly by you or inside a resource class) are destroyed when going out of scope.

提交回复
热议问题