静态对象上的shared_ptr好吗? [英] Are shared_ptr on static objects good?

查看:508
本文介绍了静态对象上的shared_ptr好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道静态对象上的智能指针是否合理.例如,假设我有一些静态资源,并且想将对该静态资源的引用传递给需要使用这些资源的其他一些对象.

I'm wondering whether smart pointers on static objects are reasonable. For example let's say I have some static resource and want to pass a reference to that static resource to some other objects which need these resource to work with.

一种方法是使用指向该资源的RAW指针.但是现在我想知道智能指针(shared_ptr)是否是更好的方法,如果是,那么如何正确执行. (智能指针也应该是静态的吗?).

One way would be to use the RAW-Pointers pointing to that resource. But now I'm wondering whether smart pointers (shared_ptr) are the better way and if so, how to do it correctly. (should the smart pointer be static as well?).

问题的背景:如果不再有持有智能指针的对象,则将释放智能指针指向的静态对象(这不是最好的主意...).

Background of the question: if no more objects holding a smart pointer anymore, the static object which the smart pointer is point to, would be freed (which is not the best idea...).

一个示例(在运行时结束时崩溃):

One example (which ends in a crash at the end of runtime):

struct SomeType {
  SomeType() { cout << "ctor..." << endl; }
  ~SomeType() { cout << "dtor..." << endl; }

  void sayHello() { cout << "Hello!" << endl; }
};


void someFunction(shared_ptr<SomeType> smartPointer) {
  smartPointer->sayHello();
}

static SomeType st;
static shared_ptr<SomeType> pt{ &st };

void anotherFunction() {

  someFunction(pt);
}

int main() {
  anotherFunction();

  cin.get();

}

推荐答案

以下两行无效.

static SomeType st;
static shared_ptr<SomeType> pt{ &st };

pt在进程生命周期的结尾被销毁时,它将为delete st. st从未分配有匹配的new.这是未定义的行为.

When pt is destroyed at the end of your process' lifetime, it will delete st. st was never allocated with a matching new. This is undefined behavior.

shared_ptr对于管理共享对象的复杂生存期非常有用,而static对象的生存期非常简单.使用shared_ptr管理static对象是不正确的,这样做没有任何好处.

shared_ptr is useful for managing the complex lifetime of shared objects while static objects have very simple lifetimes. It is incorrect to use shared_ptr to manage static objects and there would be nothing to gain in doing so.

这篇关于静态对象上的shared_ptr好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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