mora
mora

Reputation: 2287

member function pointer in constructor

I tried to use std::shared_pointer with deleter. I tried to use a member function as the deleter. However it could not compiled. Compiler gave me a error message but I could not understand why it did not work. Does someone knows why it did not work? Thank you very much.

Simplified code is following,

#include <memory>

class MemberFunctionPointerInConstructor {
public:
    MemberFunctionPointerInConstructor(void) {
        std::shared_ptr<int> a = std::shared_ptr<int>(new int(1), deleter);  // this line makes a compiler error message
    }

    void deleter(int* value) {
        delete value;
    }
};

The error message from compiler is following,

error: invalid use of non-static member function
std::shared_ptr<int> a = std::shared_ptr<int>(new int(1), deleter);
                                                                 ^

Thank you very much.

Upvotes: 7

Views: 548

Answers (4)

Yam Marcovic
Yam Marcovic

Reputation: 8141

If you want to use a non-static member function as a deleter, you have to bind it to an instance—but note that the instance would need to still be alive when the deleter is invoked. For example,

class ShorterName {
public:
    ShorterName(void) {
        using namespace std::placeholders;
        auto a = std::shared_ptr<int>(new int(1),
                   std::bind(&A::deleter, this, _1));
    }

    void deleter(int* value) {
        delete value;
    }
};

If you don't need a particular instance, you can make the function static, so it doesn't require an instance.

class ShorterName {
public:
    ShorterName(void) {
        auto a = std::shared_ptr<int>(new int(1), deleter);
    }

    static void deleter(int* value) {
        delete value;
    }
};

Upvotes: 3

marci sz
marci sz

Reputation: 108

The answer is very simple.

static void deleter(int* value) {
    delete value;
}

You must make the function static, because otherwise it might use member variables of that class, which can be only done if there is an instance for it to be done with, and here that is not the case.

Upvotes: 1

Ami Tavory
Ami Tavory

Reputation: 76297

There are several ways to solve this. If you actually mean a non-static member function, one way of doing so (not the only one) would be through a lambda function:

class MemberFunctionPointerInConstructor {
public:
    MemberFunctionPointerInConstructor() {
        std::shared_ptr<int> a = std::shared_ptr<int>(
            new int(1), 
            [this](int *p){this->deleter(p);});  
    }   

    void deleter(int* value) {
        delete value;
    }   
};  

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117866

To use a member function that isn't bound to an instance of your class you'd have to declare the method static

static void deleter(int* value) {
    delete value;
}

Upvotes: 8

Related Questions