Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::bind a std::shared_ptr parameter won't increase use_count

Tags:

c++

c++11

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.

like image 940
user1429171 Avatar asked Jan 07 '14 17:01

user1429171


2 Answers

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);
like image 105
ecatmur Avatar answered Oct 23 '22 04:10

ecatmur


the results of std::bind are not stored in a variable and are immediately discarded.

like image 1
Nicolas Louis Guillemot Avatar answered Oct 23 '22 04:10

Nicolas Louis Guillemot