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 (e.g. into an auto
):
auto bar = std::bind(func, foo);
the results of std::bind
are not stored in a variable and are immediately discarded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With