是否可以使用std :: shared_ptr ?

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

这个问题困扰了我很长时间,请帮助我,谢谢!

问题1:

{
  {
    std::shared_ptr<int*> t1 = make_shared<int *>(new int(3));
  }
 // here t1 is point heap,when the t1 died,the heap of int(3) is not free
 // in stack is correct
 {
    std::shared_ptr<int> t1 = make_shared<int>(); 
  }
 // how to reslove this ? Is `std::shared_ptr<int* >,std::shared_ptr<string* > ...` is forbiden?
}

问题2:

{
  std::shared_ptr<int> t3(new int[10], [](int*p) {delete[] p; });


}

如何使用make_shared替换?std::shared_ptr<int> t3 = std::make_shared(new int[10], [](int*p) {delete[] p; });//是错误

c++ shared-ptr smart-pointers
1个回答
1
投票

可以使用std::shared_ptr<T*>吗?

取决于您的意思。它的格式是否正确,行为是否定义明确?是的。

您需要吗?也许;可能不会;取决于用例。

std::shared_ptr<int*> t1 = make_shared<int *>(new int(3));

这很糟糕。不要使用拥有裸露的指针。

std::shared_ptr<int> t3(new int[10], [](int*p) {delete[] p; });

改为使用std::shared_ptr<int[]>

© www.soinside.com 2019 - 2024. All rights reserved.