What is the point of pointers?

后端 未结 12 1314
梦谈多话
梦谈多话 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:23

    From Wikipedia:

    C++ references differ from pointers in several essential ways:

    • It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
    • Once a reference is created, it cannot be later made to reference another object; we say it cannot be reseated. This is often done with pointers.
    • References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
    • References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.

    With the above limitations, pointers are all you got as a lightweight container to reference object, especially if you are doing something with polymorphic or dynamic. Dynamic array of pure abstract class pointers to represent windows can be an example.

    Since I am too lazy to think of an example of polymorphism I'll pull one from cplusplus.com:

    // pointers to base class
    #include <iostream>
    using namespace std;
    
    class CPolygon {
      protected:
        int width, height;
      public:
        void set_values (int a, int b)
          { width=a; height=b; }
      };
    
    class CRectangle: public CPolygon {
      public:
        int area ()
          { return (width * height); }
      };
    
    class CTriangle: public CPolygon {
      public:
        int area ()
          { return (width * height / 2); }
      };
    
    int main () {
      CRectangle rect;
      CTriangle trgl;
      CPolygon * ppoly1 = &rect;
      CPolygon * ppoly2 = &trgl;
      ppoly1->set_values (4,5);
      ppoly2->set_values (4,5);
      cout << rect.area() << endl;
      cout << trgl.area() << endl;
      return 0;
    }
    

    In the above code, pointer CPolygon * is used to reference CRectangle object and CTriangle object.

    0 讨论(0)
  • 2021-02-01 19:25

    Suppose you write a text editor. In this case, you don't know the size of the document in advance. You might be tempted to declare something like

      char Document[10000];
    

    but then certainly some day someone you will want to use your editor on a much larger document. So this attempt is futile; and what you need is a way to ask for new memory at runtime (instead of compile time).

    The C++ way of doing this is using the operator new, which returns a pointer to the freshly allocated memory:

      char* pDocument = new char[getSizeOfDocument()];
    

    (Note that this example is oversimplified. In real life, you would certainly not do it like this but instead use something like std::string and std::vector, which internally do this allocation for you.)

    0 讨论(0)
  • 2021-02-01 19:29

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

    struct A {
      vector<const B *> *pBees;
      A() : pBees(nullptr) {}
      void notice_bee(const B *pB) { 
        if (!pBees)
          pBees = new vector<const B *>;
        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.

    0 讨论(0)
  • 2021-02-01 19:29

    It sounds to me like you haven't yet learned about dynamic memory allocation. There are two ways to allocate memory in C++: statically and dynamically. You are already familiar with static allocation (i.e. - declaring variables). This is great if you know at the time of writing your program exactly how many variables (or rather, memory) you need.

    But what if you don't? For example, let's say you're reading that contains a bunch of numbers you need to keep track of. Why? I don't know but that's not the point.

    Well you could start with an array:

    int array[100];
    

    But what if there are more than 100 numbers in the file? Eventually you'll want a more flexible solution:

    int *array = new int[size];
    // do stuff
    delete [] array;
    

    This gives you a lot more flexibility and lets you create more dynamic data structures.

    0 讨论(0)
  • 2021-02-01 19:34

    Pointers are also great for passing a mutable argument to a function so that the caller can "see the change". You may wonder, "but why not use a reference?". I like Google's argument:

    http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments

    0 讨论(0)
  • 2021-02-01 19:34

    At the most basic level, pointers allow you to associate disjoint blocks of memory. A simple (contrived, admittedly) example of where pointers could help you would be in an algorithm that requires an array of 1000000000000 integers. Such an array would be too large to fit within the RAM of the machine on which I am typing right now if I tried a definition such as:

    int bigMatrix[1000000000000]; // I can't allocate this much contiguous memory
    

    However, if I create a single array of pointers, I can keep the sub-arrays on a middle-sized disk array.

    int *bigMatrix[1000000]; // Each pointer refers to a sub-array 
                             // of 1000000 elements on disk
    

    Admittedly, I will have to write code to page in those sub-arrays if / when the user requires them, including hiding the array notation behind an accessor method. That said, pointers allow me to create the ad-hoc associations that I need when I need them.

    0 讨论(0)
提交回复
热议问题