当前位置 : 主页 > 编程语言 > c++ >

c++指针的坑

来源:互联网 收集:自由互联 发布时间:2021-06-23
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 thre

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++指针合法有三种情况:

  1.指向一个对象   

       2.指向一个对象结束位置下一个字节

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

  3.指向空指针

 

其它情况为非法指针

非法指针产生的情景:

  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;

  }

       //指向对象已被回收,编译不会报错

  (**pp).showi();//build-in type 内存内容还未被擦除或覆盖
  (**pp).showch();//动态分配的内存内容已被擦除

}

 

result:

                            

 

 

 2.动态分配类成员空间未实现复制构造函数

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()

{
  Message motto1("Fallout4.");
  Message motto2(motto1);//当motto1或motto2其中一个生命周期结束另一个会产生非法指针,应实现复制构造函数使两者指向对象不同
}

网友评论