What is the point of pointers?

后端 未结 12 1502
梦谈多话
梦谈多话 2021-02-01 18:49

What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?

12条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 19:29

    From an architectural perspective, pointers are an economical way to model a 0 .. n relationship:

    struct A {
      vector *pBees;
      A() : pBees(nullptr) {}
      void notice_bee(const B *pB) { 
        if (!pBees)
          pBees = new vector;
        pBees.push_back(pB)
      }
      ~A() { 
        delete pBees; // no need to test, delete nullptr is safe
      }
      size_t bees_noticed() { return pBees ? pBees->size : 0 }
    };
    

    If the vast majority of A objects will never need to pay attention to any B objects, there is no reason why every A object should have a zero-length vector. Under Gnu C++ 4.0.1, sizeof(vector) is 12; sizeof(vector *) is 4.

提交回复
热议问题