首页 > 编程语言 > 详细

c++指针的坑

时间:2019-10-20 19:52:36      阅读:53      评论:0      收藏:0      [点我收藏+]

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其中一个生命周期结束另一个会产生非法指针,应实现复制构造函数使两者指向对象不同
}

c++指针的坑

原文:https://www.cnblogs.com/DkMoon/p/11708470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!