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.
I am using clang++
Apple LLVM version 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
:
Foo(const Foo &foo):
m_p{foo.m_p}
{
printf("copy\n");
}
Second, your bind
results in a temporary which is immediately discarded; you should capture it (eg into an auto
):
auto bar = std::bind(func, foo);
std::bind
的结果不存储在变量中,并立即被丢弃。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.