使用析构函数= delete; [英] Uses of destructor = delete;

查看:542
本文介绍了使用析构函数= delete;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下类:

struct S { ~S() = delete; };

出于以下问题的目的:我无法创建 S的实例就像 S s {}; ,因为我无法销毁它们。

如评论中所述,我仍然可以创建通过执行 S * s = new S; 来创建实例,但我也无法删除它。

因此,我只能看到删除的析构函数是这样的:

Shortly and for the purpose of the question: I cannot create instances of S like S s{}; for I could not destroy them.
As mentioned in the comments, I can still create an instance by doing S *s = new S;, but I cannot delete it as well.
Therefore, the only use I can see for a deleted destructor is something like this:

struct S {
    ~S() = delete;
    static void f() { }
};

int main() {
    S::f();
}

也就是说,定义一个只公开一堆静态函数的类,并禁止

That is, define a class that exposes only a bunch of static functions and forbid any attempt to create an instance of that class.

删除的析构函数的其他用途(如果有)是什么?

What are the other uses (if any) of a deleted destructor?

推荐答案

如果您有一个永远不应该删除的对象,请删除 d或将其存储在堆栈中(自动存储),或存储为另一个对象的一部分, = delete 将阻止所有这些操作。

If you have an object which should never, ever be deleted or stored on the stack (automatic storage), or stored as part of another object, =delete will prevent all of these.

struct Handle {
  ~Handle()=delete;
};

struct Data {
  std::array<char,1024> buffer;
};

struct Bundle: Handle {
  Data data;
};

using bundle_storage = std::aligned_storage_t<sizeof(Bundle), alignof(Bundle)>;

std::size_t bundle_count = 0;
std::array< bundle_storage, 1000 > global_bundles;

Handle* get_bundle() {
  return new ((void*)global_bundles[bundle_count++]) Bundle();
}
void return_bundle( Handle* h ) {
  Assert( h == (void*)global_bundles[bundle_count-1] );
  --bundle_count;
}
char get_char( Handle const* h, std::size_t i ) {
  return static_cast<Bundle*>(h).data[i];
}
void set_char( Handle const* h, std::size_t i, char c ) {
  static_cast<Bundle*>(h).data[i] = c;
}

在这里,我们有不透明的 Handle 可能不会在堆栈上声明或动态分配。我们有一个从已知数组中获取它们的系统。

Here we have opaque Handles which may not be declared on the stack nor dynamically allocated. We have a system to get them from a known array.

我相信上面没有什么是未定义的行为。无法销毁 Bundle ,也可以在其位置创建一个新的销毁。

I believe nothing above is undefined behavior; failing to destroy a Bundle is acceptable, as is creating a new one in its place.

不必公开捆绑包的工作方式。只是不透明的 Handle

And the interface doesn't have to expose how Bundle works. Just an opaque Handle.

现在,如果代码的其他部分需要知道所有内容,则此技术很有用句柄位于该特定缓冲区中,或者以特定方式跟踪它们的生存期。可能也可以通过私有构造函数和朋友工厂函数来处理。

Now this technique can be useful if other parts of the code need to know that all Handles are in that specific buffer, or their lifetime is tracked in specific ways. Possibly this could also be handled with private constructors and friend factory functions.

这篇关于使用析构函数= delete;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆