c++ - 避免 `delete[]` 接受隐式指针转换?

标签 c++ operator-overloading delete-operator conversion-operator

我有一个带有指向指针的隐式转换运算符的类。取消分配该指针无效。与 delete[] 运算符一起使用时,我可以阻止转换为指针吗?我想要一个编译时错误。对于 free 函数,我可以删除将类作为参数的重载。

void foobar(double*){}

struct A {
  // Please pretend I have a good reason for doing this.
  operator double*() const { return nullptr; }
};

void free(A&) = delete;

int main(){
  A a;
  
  // Just works TM
  foobar(a);

  // This compiles :(
  delete[] a;
  // This does not :)
  //free(a);
  return 0;
}

我认为需要一些巧妙的方法才能达到预期的效果。


隐式转换的用例:假设A实现了一个作用域数组。转换使得 A 几乎成为 alloc/dealloc 对的替代品。需要显式转换的模板和迭代器。否则,类 C 函数的调用位置保持不变。

最佳答案

作为解决方法,您可以通过使转换不明确来防止与 delete[] 运算符一起使用时转换为指针。

但是,根据代码其余部分的情况,这可能会导致所需用例出现不期望的歧义。

struct A {
  operator double*() const { return nullptr; }
  operator void*() const { return nullptr; }
};

关于c++ - 避免 `delete[]` 接受隐式指针转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64562257/

相关文章:

c++ - 防止在基类和派生类上使用 delete,同时允许使用 new

c++ - 当构造函数抛出异常时删除运算符段错误

c++ - 双向链表上的删除函数

c++ - 使用 Windows 密码学函数 C++ 对哈希进行签名

c++ - 为多字段类重载 operator<

c++ - 不能通过引用传递给线程

c++ - 重载运算符 = 用于类型转换

java - 是否可以在 Java 中重载运算符?

c++ - 指针的两种不同语法约定?

c++ - 使用指针重新排列数组中的数字