如果动态分配了一个数组,但是却用 delete p 的方式释放,没有用[],则编译时 没有问题,运行时可能不会发生错误,但实际上会导致动态分配的数组没有被完 全释放。
用 delete 释放空间后,指针的值仍是原来指向的地址,但指针已无效(重复释放 将出错)
例:
#include<iostream> usingnamespace std; voidinc(int *p, int Length){ for (int i = 0; i < Length; i++) p[i]++; } intmain(){ int *p; int Length, i; cout << "Enter the lenght you want: "; cin >> Length; p = newint[Length]{1,3,5}; inc(p, Length); for (i = 0 ; i < Length; i++) cout << *(p+i) << " "; delete []p; }
#include<iostream> usingnamespace std; classA { public: A(int x) { cout << "This is a parameterized constructor"; } A() = default; }; intmain(){ A a; //call A() A x(1); //call A(int x) cout<<endl; return0; }
弃置函数:=delete
任何弃置函数的使用都是非良构的(程序无法编译)
删除的函数是隐式内联的,这一点非常重要,删除的函数定义必须是函数的首次声明
例: classA { public: A(int x): m(x) { } // Delete the copy constructor A(const A&) = delete; // Delete the copy assignment operator A& operator=(const A&) = delete; int m; };
以下方法是将函数声明为已删除的正确方法: classC { public: C(C& a) = delete; }; 但是以下尝试声明删除函数的方法会产生错误: // incorrect syntax of declaring a member function as deleted classC { public: C(); }; // Error, the deleted definition of function C must be the first declaration of the function. C::C() = delete;