简体   繁体   中英

Pointers to object as class member in “modern C++”

So one rule of thumb I've heard with respect to modern C++ style is that one shouldn't need to use new or delete, and one should instead use smart pointers. So how to go about this when I have a class where one of the members is a pointer to another object. By using a smart pointer I can avoid the need to delete, but I still need to create the object with new. Eg is the below "canonical" modern C++ style, or how should one go about this?


#include 
#include 

class B {
public:
    B () { std::printf("constructing B\n");}
    ~B () { std::printf("destroying B\n");}
};

class A {
public:
    A () 
    { 
        std::printf("constructing A\n");
        b = std::unique_ptr(new B());
    }
    ~A () { std::printf("destroying A\n");}

private:
    std::unique_ptr b;
};

int main()
{
    A a;
    return 0;
}

You use new . There's nothing wrong with using new , it should just be used as rarely as possible.

( delete on the other hand, should almost never be used, since its usage should always be encapsulated in some sort of RAII handle like a smart pointer or a container.)


Note that when using smart pointers, you should always assign the result of new to a named smart pointer or use reset . In your case, you'd want to use:

A() : b(new B()) { }

or:

A()
{
    std::unique_ptr<B> x(new B());
    b = std::move(x);
}

or:

A() { b.reset(new B()); }

(For why this is important, see the "Best Practices" section of the boost::shared_ptr documentation .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM