c ++ pointers pit

1. It can point to an object.
2. It can point to the location just immediately past the end of an object.
3. It can be a null pointer, indicating that it is not bound to any object.
4. It can be invalid; values other than the preceding three are invalid.

c ++ pointer lawful in three ways:

  1. point to an object   

       2. The end of the next target point to a location of a byte

            exp.            for(vector<int>::iterator iter = vecInt.begin(); iter != vecInt.end(); ++iter)

  3. Point null pointer

 

Otherwise, it is invalid pointer

Illegal pointer scenarios generated:

  The non-null pointer to an object pointer pointing to the end of the life cycle of 1

class A
{
  int i1 = 0;
  double d1 = 0;
  char *ch = nullptr;
 public:
    A()
  {
    i1 = 1;
    d1 = 1;
    ch = (char *)malloc(4);
    strcpy_s(ch,3,"vi");
  }
         void showch()
  {
    cout << ch << endl;
  }
    void showi()
  {
    cout << i1 << endl;
  }
    ~A()
  {
    free(ch);
  }
};

 

  int main()
{
  double dval = 2.03;
  A **pp = nullptr;

  for (int i = 0; i < 1;i++)
  {
    A a11;
    a11.showch();
    a11.showi();
    A *p= &a11;
    pp = &p;

  }

       // point to objects that have been recovered, the compiler will not complain

  (** pp) .showi (); // build-in type memory contents not yet erased or overwritten
  (** pp) .showch (); // dynamically allocated memory that has been erased content

}

 

result:

                            

 

 

 2. Dynamic allocation space class members unimplemented copy constructor

class Message

{
  private:
    char* pmessage;
  public:
    void ShowIt() const

    {
      cout <<endl <<pmessage;
   }

    Message(const char* text = "Defaut message")

  {
    pmessage = new char[strlen(test) + 1];
    strcpy_s(pmessage,strlen(text) + 1,text);
  }
    ~CMessage()  

       {

              delete[] pmessage;

  }
};

  int main ()

{
  The Message motto1 ( "Fallout4.");
  The Message motto2 (motto1); // if motto1 or motto2 wherein the other end of a life cycle will generate an illegal pointer, copy constructor should realize that the two different pointing object
}

Guess you like

Origin www.cnblogs.com/DkMoon/p/11708470.html
Recommended