防止析构函数在C ++中运行 [英] Preventing a Destructor from Running in C++

查看:166
本文介绍了防止析构函数在C ++中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保对象的析构函数不会 运行。除了将对象放在堆上而不调用delete之外,有什么办法吗?

解决方案

不推荐,但这里有另一种方法:

  char缓冲区[sizeof(T)+ alignof(T)]; 
char * aligned_buffer = buffer + alignof(T) - reinterpret_cast< intptr_t>(buffer)%alignof(T);
T * object = new(aligned_buffer)T;但是,虽然这意味着编译器不会自动调用析构函数,但是程序员仍然可以:

  object->〜T() 

当然,堆分配也是如此:

 删除对象; 

为了防止这种情况,你必须让析构函数不可访问:

  struct T 
{
private:
〜T(){};
};

或真的无法存取(相关:为什么只有在声明自定义构造函数时才能访问基类析构函数?):

  class indestructible_base 
{
〜indestructible_base();
};

struct T:indestructible_base
{
};


I would like to ensure that an object's destructor does not run. Is there any way to do this other than putting the object on the heap and not calling delete?

解决方案

Not recommended, but here's another way:

char buffer[sizeof(T) + alignof(T)];
char* aligned_buffer = buffer + alignof(T) - reinterpret_cast<intptr_t>(buffer) % alignof(T);
T* object = new (aligned_buffer) T;

However, although this means the compiler won't automatically call the destructor, the programmer still can:

object->~T();

Of course, that's also true with heap allocation:

delete object;

To prevent that, you'll have to make the destructor inaccessible:

struct T
{
private:
   ~T() {};
};

Or really inaccessible (related: Why must a base class destructor be accessible only when a custom constructor is declared?):

class indestructible_base
{
    ~indestructible_base();
};

struct T : indestructible_base
{
};

这篇关于防止析构函数在C ++中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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