【发布时间】:2019-06-13 16:35:23
【问题描述】:
我正在阅读一些代码库,但我不太明白为什么下面的函数会将reference (&) 返回到std::shared_ptr。我在this stackoverflow question 中读到我们应该按值返回std::shared_ptr,否则我们将无法正确增加引用计数。
所以我只是想猜测原因。
- 是否与成员函数有关
static?或者返回值为static? - 和
thread有关系吗 顾名思义?谁能给我指点阅读或 给点方向?
class A {
public:
A() {...}
~A() {...}
...
static std::shared_ptr<A>& ThreadLocal() {
static std::shared_ptr<A> inst = std::make_shared<A>();
if (inst == nullptr) {
inst = std::make_shared<A>();
}
return inst;
}
static void Shutdown() {
ThreadLocal().reset();
}
private:
...
}
【问题讨论】:
-
ThreadLocal使用static而不是thread_local?什么平分? -
TBH 对我来说似乎有点可疑。
-
static在声明中始终适用于被声明的名称。
标签: c++ c++11 return smart-pointers return-type