在写回复时,我写了一些代码来挑战我对 const 指针如何工作的假设。我曾假设 const 指针不能被 delete 函数删除,但正如您从下面的代码中看到的那样,情况并非如此:
#include <new>
#include <string.h>
class TestA
{
private:
char *Array;
public:
TestA(){Array = NULL; Array = new (std::nothrow) char[20]; if(Array != NULL){ strcpy(Array,"Input data"); } }
~TestA(){if(Array != NULL){ delete [] Array;} }
char * const GetArray(){ return Array; }
};
int main()
{
TestA Temp;
printf("%s\n",Temp.GetArray());
Temp.GetArray()[0] = ' '; //You can still modify the chars in the array, user has access
Temp.GetArray()[1] = ' ';
printf("%s\n",Temp.GetArray());
//Temp.GetArray() = NULL //This doesn't work
delete [] Temp.GetArray(); //This works?! How do I prevent this?
}
我的问题是,我如何将用户访问权传递给指针(以便他们可以像使用 char 数组一样使用它),同时通过最好抛出某种投诉或异常来使删除函数无法删除它?