有没有办法阻止在C++中通过声明删除指针?
我试过没有运气的代码.
const int* const foo()
{
static int a;
return &a;
}
int main()
{
const int* const a = foo();
*a = 1; //compiler error, const int*
a++; //compiler error, int* const
delete a; //no compiler error, I want to have compiler error here
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*abe 39
您不能以阻止调用delete指针的方式声明指向任意类型的指针.删除指向const(T const*)的指针解释了为什么会这样.
如果它是指向自定义类的指针,则可以将delete运算符设为私有:
class C {
void operator delete( void * ) {}
};
int main() {
C *c;
delete c; // Compile error here - C::operator delete is private!
}
Run Code Online (Sandbox Code Playgroud)
你当然不应该将析构函数设为私有(正如其他人所建议的那样),因为它也会避免在堆栈上创建对象:
class C {
~C() {}
};
int main() {
C c; // Compile error here - C::~C is private!
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*son 16
简单的答案是否定的.无法阻止在指向内置类型的指针上调用删除.
附录:
但是我遇到了类似的情况..我的解决方法是停止使用普通指针,因此无需担心删除.在我的情况下,共享指针是有意义的,但它是一个独特的指针或类似可能就足够了.
//Custom do nothing deleter.
template<typename T> dont_delete( T* ) { /* Do Nothing */ }
shared_ptr<const int> const foo()
{
static int a;
return shared_ptr<const int>(&a, &dont_delete<const int> );
}
shared_ptr<const int> const bar()
{
return shared_ptr<const int>(new int(7) );
}
main()
{
shared_ptr<const int> p1 = foo();
shared_ptr<const int> p2 = bar();
//p1s data _not_ deleted here,
//p2s data is deleted here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12290 次 |
| 最近记录: |