阻止使用静态生命周期创建对象

问题描述 投票:2回答:2

我们可以阻止创建具有静态生命周期的对象,同时允许使用自动生命周期创建对象吗?

如果我们想要阻止用户创建具有自动持续时间的类的实例,我们可以将析构函数设为私有。如果我们想阻止用户使用动态分配创建实例,我们可以将operator new设为私有。

我认为不可能阻止用户创建具有静态存储持续时间的对象,因为唯一的区别是生命周期。但也许这里的一些专家可以设计出一种方法。

c++ static stack heap
2个回答
3
投票

在编译时没有语言功能。但在运行时,您可以使用以下技术来限制它。假设你不想在MyObject存储区域上使用static,那么在析构函数中添加代码为:

bool ALLOW_OBJECTS = false;  // global variable
struct MyObject  // class body
{
 ~MyObject ()
  {
    if(ALLOW_OBJECTS == false)
      <print error message>
    // ...
  }
};

现在,在您的main()方法中,您可以使用ALLOW_OBJECTS

int main ()
{
  ALLOW_OBJECTS = true;  // objects can be created now
// ... other code
  ALLOW_OBJECTS  = false;  // reset to 'false' before main() ends
}

现在,在static完成后,在main()存储中声明的变量消失了它们的生命周期(调用析构函数)。因此,如果在static存储上声明了变量,则其析构函数将打印错误消息(在文件或标准输出中)。

通过此检查,您的1次执行测试运行可能会失败,但您可以在找到错误消息数后手动更正代码。因此,在您的生产代码中,您可以删除所有这些调试语句,并且您将拥有没有任何static存储对象的代码! (不适用于POD和指针)。


0
投票

在wikibooks Requiring or Prohibiting Heap-based Objects上有一张收据。

关键是要使类析构函数受到保护,因此使用静态创建的对象将生成编译时错误。缺点是您必须为您的类实现并调用单独的delete方法。

class HeapOnly {
  public:
    HeapOnly() {} 
    void destroy() const { delete this; }
  protected:
    ~HeapOnly() {}
};
HeapOnly h1;     // Destructor is protected so h1 can't be created globally
HeapOnly func()  // Compiler error because destructor of temporary is protected
{
  HeapOnly *hoptr = new HeapOnly; // This is ok. No destructor is invoked automatically for heap-based objects
  return *hoptr;
}
int main(void) {
  HeapOnly h2; // Destructor is protected so h2 can't be created on stack
}
© www.soinside.com 2019 - 2024. All rights reserved.