c++实战吐槽(我还是太年轻了)

时间:2023-03-09 02:26:34
c++实战吐槽(我还是太年轻了)

习惯了用java, 现在切换到c++遇到了一些很滑稽的问题, 特此记录。

一. 使用了野指针

都知道不能使用野指针, 指针定义后,要初始化为null, 我在项目里面默认构造函数里面确实初始化为null了, 但是在拷贝构造函数里面忘了,结果。。。

class A{

  public:

    A():p(0){}

A(const A& other){

if (p != NULL) delete []p;

....

    }

private:

    char *p;

}

二. 重复free内存(当时我找了好久的这个Bug, eclipse太坑,出错提示信息无法定位到错误, adb locat|ndk_stack 倒是可以让我定位的代码行, 但是如果是指针问题,定位到代码行也是很难找到原因,想用单步调试的,但是eclipse老是单步调试失败)

class A{

  public:

    A():p(0){}

void set(char *p){

if (this->p != NULL){

delete[] this->p;

}

.....

}

A & operator =(const A &other){

      if (this->p != NULL) delete []this->p;

set(other.p);

.....

    }

private:

    char *p;

}

三.方法的返回是拷贝的值,每次调用方法返回的对象不是同一个对象, 像我没注意就出现了无限循环

class A{

public:

list<string> getlist(){

return this->alist;

}

A(const A& other){

for (list<string>::iterator ite = other.getlist().begint; ite != other.getlist().end(); ite++){ //other.getlist()返回的每次都是不同地址,所以条件判断就无效了,改成 list<string> temp = other.getlist();用temp代替other.getlist()就可以了。

this->alist.push_back(*ite);

      }

}

private:

     list<string> alist;

};

四. 迭代器遇到的问题:

class A{};

int main(){

list<A> alist;

list<A>::iterator ite = alist.begin();

A aobj;

*ite = aobj; //这里ite = alist.end();无效的地址,不可以赋值

}