[英]std::bind a std::shared_ptr parameter won't increase use_count
The following code: 以下代码:
#include <stdio.h>
#include <memory>
#include <functional>
struct Foo{
Foo():
m_p(std::make_shared<int>())
{}
Foo(const Foo &foo)
{
printf("copy\n");
}
std::shared_ptr<int> m_p;
};
void func(Foo foo)
{}
int main()
{
Foo foo;
std::function<void (void)> f = std::bind(func, foo);
printf("use count : %ld\n", foo.m_p.use_count());
f();
}
got result: 得到的结果:
copy
copy
use count : 1
copy
Since Foo is copied, I thought m_p's use_count should be 2. 由于Foo被复制,我认为m_p的use_count应为2。
I am using clang++ 我正在使用clang ++
Apple LLVM version 5.0 (clang-500.2.79) Apple LLVM 5.0版(clang-500.2.79)
I compile the code in debug mode. 我在调试模式下编译代码。
There are two issues with your code. 您的代码有两个问题。
First, your copy constructor isn't copying m_p
: 首先,您的复制构造函数不是复制
m_p
:
Foo(const Foo &foo):
m_p{foo.m_p}
{
printf("copy\n");
}
Second, your bind
results in a temporary which is immediately discarded; 其次,你的
bind
导致一个临时的,立即丢弃; you should capture it (eg into an auto
): 你应该抓住它(例如进入
auto
):
auto bar = std::bind(func, foo);
std::bind
的结果不存储在变量中,并立即被丢弃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.