简体   繁体   中英

C++ - When to use pointers to class data members?

I've been coding in C++ and I was wondering if someone could help me with the general reason why we sometimes need to make pointers to class members and other times we don't.

For example if we are coding a Binary Tree

I implement it as

class BinaryTree{

    BinaryTree * left;
    BinaryTree * right;
    int val;

    public:
        BinaryTree(int v) {left = NULL; right = NULL; val = v;}
        //implementation of any other neccessary functions
};

I use the BinaryTree pointers to left and right, because we can't do it without the pointer since BinaryTree does not exist at that point in time.

Are there any other reasons to do this? Is there anyway around this?

Also, if we put pointer member functions, will the implicit destructor handle the deletion of them?

Thanks for your time.

This is a box:

一个盒子,在这里代表一个结构

it has a volume of about one cubic meter, so it can only store objects that have total volume of one cubic meter. And it definitely can't store two identical boxes as itself. Note that each one of these two boxes would also need to contain two boxes like it, and so on, and so on.

This is a struct :

struct BinaryTree {
    BinaryTree left;
    BinaryTree right;
    int val;
};

it has a finite size equal to sizeof(BinaryTree) , so it can only store objects that have total size less or equal to sizeof(BinaryTree) . And it definitely can't store two values of type BinaryTree . Note that each one of these two values would also need to store two values like it, and so on, and so on.

Since the struct instances can't contain other instances of the same struct, and we need to define relations between them, and trees are definitely hierarchical, we use pointers here.

Note that the only thing that so called raw pointer to T (that is, T* ) does, is to point to T . Since pointing is the only task of such pointer, destruction won't destroy the pointed object, only the pointer .

There exist types that behave like pointers, but also do other tasks, like managing lifetime of pointed object. These are C++11's std::unique_ptr , and std::shared_ptr , and many others. I highly recommend using them.

Objects often hold members that only need to be created based on run time conditions or parameters. You want to delay creation as late as possible. This is a common case for using pointers.

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