member function pointer in constructor - c++

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.

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;
}

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;
}
};

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;
}
};

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.

Related

C++ invalid function type casting

I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:
void SomeFunction() { }
class A {
public:
typedef std::function<void(void)> AFunction;
static void AMethod(AFunction f) { f(); }
};
class B {
public:
void B1Method() { }
void BCorrectCall() { A::AMethod(SomeFunction); }
void BIncorrectCall() { A::AMethod(B1Method); }
};
Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!
Use a lambda:
A::AMethod([this]{B1Method();});
It doesn't matter in this case, but if you wanted to store AFunction f and use it after the call to AMethod, you'd have to ensure that the B instance (the address of which is saved in the lambda) says alive as long as you use the function.
C++17 allows you to capture *this instead, which will copy the entire B instance into lambda, but normally it's not what you want.
You could do something similar with std::bind (see the other answer), but lambdas are more flexible.
B1Method is not void(*)(void), it's void(B1::*)(void).
You may do
void BIncorrectCall() { A::AMethod(std::bind(&B1::B1Method, this)); }
};
The issue is that B::B1Method() is a non-static member function in B and, therefore, it needs to be called on an instance of B.
If the implementation of B1Method() doesn't use any non-static data member of B and it doesn't call any other non-static member function of B, then simply declaring it as static will work with your current implementation of BIncorrectCall() as you will no longer need to call B1Method() on an instance of B:
class B {
public:
static void B1Method() { } // static now
void BCorrectCall() { A::AMethod(SomeFunction); }
void BIncorrectCall() { A::AMethod(B1Method); } // no change
};
Otherwise, you have to keep an object of type B whenever you want to call B1::B1Method().
The easiest way is to make it static and so there is no this object, but if you need it (the this object), you can use lambdas:
class B {
public:
void B1Method() { }
void BCorrectCall() { A::AMethod(SomeFunction); }
void BIncorrectCall() {
std::function<void(void)> el = [&](){this->B1Method();};
A::AMethod(el);
}
};
The problem is that 'B1Method' is not a simple function - it's a class method. That means that when you call myB.B1Method(), you're actually calling 'B1Method(&myB)', effectively passing the this pointer as a hidden argument - so you can't convert M1Method to a std::function without specifying which object it should act on.
One approach that should work is using std::bind to construct a callable object from a combination of an object (class instance) and the method. Something like:
void BNowCorrectCall() { A::AMethod(std::bind(&B::B1Method, this)); }

Does C++ have a defined way to pass a pointer to a member function of a member object of a class?

Let's say I have some function:
void myFunction(void (MyClass::*function)(int), MyClass& myClass) {
(myClass.*function)(1);
}
Which is called as follows:
class MyClass {
int value;
void setValue(int value) {
this->value = value;
}
}
MyClass myClass;
myFunction(&MyClass::set_value, myClass);
This function takes the object myClass and says to call its member function setValue, which it calls with the parameter set to 1.
Before I realized C++ had support for passing member functions as as parameters, I had manually set my code to take in a object and function pointer and then determine the offset between their addresses. This offset could then be saved to call the same member function if given a different instance of the same type of object.
But yeah, then I discovered you can just do Class::*function which (I assume) does exactly what I had previously built/described.
Which leads me to my issue, let's say I have the same function as before, except I change my class structure a bit:
class MyClass {
ChildClass childClass;
}
class ChildClass {
int value;
void setValue(int value) {
this->value = value;
}
}
Is there then a way in C++ to pass the setValue function into myFunction given that setValue is now within the ChildClass object within MyClass?
The most obvious solution would be to add a setValue member function to MyClass which calls the setValue function within its childClass object, like so:
class MyClass {
ChildClass childClass;
void setValue(int value) {
this->childClass.setValue(value);
}
}
class ChildClass {
int value;
void setValue(int value) {
this->value = value;
}
}
MyClass myClass;
myFunction(&MyClass::setValue, myClass);
However, due to the semantics of the project I am working on this would not be a desirable solution. Thus, I was curious about whether or not there is a way to achieve this in C++. If not, I can certainly just implement it manually (it would be the same as before, except you would save the offset between the childClass member and MyClass as well as the offset of the setValue member and ChildClass), but naturally I'd like to know if there is a more "built-in" way of achieving this.
Is there then a way in C++ to pass the setValue function into myFunction given that setValue is now within the ChildClass object within MyClass?
There is a way by adding a level of indirection. That level of indirection is polymorphic function wrapper std::function. myFunction can take a std::function argument, which can be initialized with arbitrary accessor functions, including labdas. E.g.:
#include <functional>
struct ChildClass {
int value;
void setValue(int value) {
this->value = value;
}
};
struct MyClass {
ChildClass childClass;
};
void myFunction(std::function<void(MyClass&, int)> const& f, MyClass& myClass) {
f(myClass, 1);
}
int main() {
MyClass myClass;
myFunction([](MyClass& a, int b) { a.childClass.setValue(b); }, myClass);
}
Using std::function your can get rid of MyClass& argument and expect the user to provide the required object inside std::function captured by the lambda expression:
void myFunction2(std::function<void(int)> const& f) {
f(1);
}
int main() {
MyClass myClass;
myFunction2([&myClass](int b) { myClass.childClass.setValue(b); });
}
Note that std::function can store at least sizeof(void(Undefined_class::*member_pointer)()) inside the object without allocating heap memory. The C++ standard doesn't require that, however, it seems that the reason for this optimization is that using std::function for member function pointers is not much worse than using member function pointers directly. Or, in other words, if you replace member and member function pointers in your code with std::function, your application won't be penalised by extra memory allocations for that†. With gcc on x86_64 that results in 16 bytes of inline storage in std::function, which can store a lambda capture object with 2 object references.
† The size of std::function is still larger than that, though, and it is a non-trivial type, so it cannot be passed or returned in registers.
There is a solution with c++17 fold expressions:
#include <iostream>
struct S
{
int foo() {return 1;}
};
struct T
{
S s;
};
template<class ... Args>
int call(T &t, Args... args)
{
return (t .* ... .* args)();
}
int main()
{
T t{};
std::cout << call(t, &T::s, &S::foo);
}
You have to explicitly give the whole "path" to the member function, but I think this is unavoidable (just from a logical point of view). This scales to an arbitrary level of indirection. You can also template also the T and it shouldn't be to bad to add functions arguments.
Does this do what you want?
class ChildClass {
public:
int value;
void setValue(int value) {
this->value = value;
}
} ;
class MyClass {
public:
ChildClass childClass;
} ;
static void myFunction(void (ChildClass::*f)(int), MyClass& myClass) {
(myClass.childClass.*f) (1) ;
}
int main() {
MyClass myClass;
myFunction(&ChildClass::setValue, myClass);
}
Note the semi-colons after the class definitions.

Invoke a templated member from a c-function using void pointer

My c++ code has to work with an underlying c-library. I have a c++ object that looks somewhat like this:
template <typename T>
class MyClass
{
public:
explicit MyClass(int x)
: mVar(x)
{
}
private:
int mVar;
};
Later in my c++ code I do the following:
auto p = new MyClass<int>(10);
call_c_lib_function((void*) p);
The c function saves the pointer 'p' in a larger c-structure. Later when the large
c object is getting destroyed, it invokes the delete handler.
void
c_delete_handler(void* data)
{
// data is holding the pointer value 'p' from above.
}
Since the object is getting destroyed, I need to free the object that allocated.
Per the c++ spec, 'delete void_ptr' is undefined since it doesn't know how to
invoke the appropriate destructor. How do I invoke delete on the appropriate
template object?
One solution I could think of was to create a wrapper structure around my MyClass pointer.
struct Wrapper {
enum template_type {
template_int,
template_double,
template_string,
...
};
int template_type;
void* obj_ptr;
};
before callign the call_c_lib_function, I'd do the following:
auto p = new MyClass<int>(10);
auto w = new Wrapper()
w.template_type = Wrapper::template_int;
w.obj_ptr = (void*) p;
call_c_lib_function((void) w);
and now in the delete handler, I can do the following:
void
c_delete_handler(void* data)
{
Wrapper* w = (Wrapper*) data;
switch (w->template_type) {
case Wrapper::template_int:
delete (MyClass<int>*) w->obj_ptr;
break;
case Wrapper::template_double:
delete (MyClass<double>*) w->obj_ptr;
break;
...
}
}
Is this a correct approach? is there a better alternative?
Would appreciate any inputs. Thanks.
Instead of using Wrapper, use a base class, if that's an option.
class MyBase
{
public:
virtual ~MyBase() {};
};
template <typename T>
class MyClass : public MyBase
{
public:
explicit MyClass(int x) : mVar(x) {}
private:
int mVar;
};
and then
void c_delete_handler(void* data)
{
Base* basePtr = reinterpret_cast<Base*>(data);
delete basePtr;
}
This approach obviates the need for keeping track of whether MyClass was instantiated using int, double, std::string, or ....

Function pointer of a member function of the current instance

I want to get the function pointer of a member function of the current instance of a C++ class. Then I want to add that function pointer to a global registry.
I can't create the instance in a separate location and add the function pointer there. It should get added within this instance.
This is what I have done. But it doesn't work as intended. Is there anything I am doing wrong here?
Example
In MyClass.h
class MyClass
{
public:
MyClass();
~MyClass();
typedef int (MyClass::*fpointer)(int);
int foo(int val);
private:
void addFuncPointer();
}
In MyClass.cpp
MyClass::MyClass()
{
addFuncPointer();
}
int MyClass::foo(int val)
{
// Function Definition
}
void MyClass::addFuncPointer()
{
fpointer funct = &MyClass::foo;
//I am adding this function pointer to a global registry.
GlobalRegistry.add(globalindex, funct);
globalindex++;
}
In Main.cpp
int main()
{
MyClass* cls = new MyClass();
GlobalRegistry.getFunctionPointer(validindex)->call();
return 0;
}
The problem that you are experiencing is caused by the fact that all objects of a class share the same code for their member functions. So if you want to invoke a member function for a particular instance, you're gonna need to save both, a pointer to the instance and a pointer to the member function.
Since C++11 this can be wrapped into a function object:
struct Foo {
void func() { /* ... */ }
} foo;
auto mem_func = std::bind(&Foo::func, &foo);
mem_func();

How to call a non static member function from a static member function without passing class instance

I need to call a non static member function from a static member function of the same class.
The static function is a callback. It can receive only void as data, though which i pass a char*. So i cannot directly provide the class instance to the callback. I can pass a structure instead of char to the callback function. Can anyone give eg code to use the non static member function in a static member function . and use the structure in the static member function to use the instance of the class to call the non static member function?
Normally such a callback would look like this:
void Callback( void* data)
{
CMyClass *myClassInstance = static_cast<CMyClass *>(data);
myClassInstance->MyInstanceMethod();
}
Of course, you need to make sure, data points to an instance of your class. E.g.
CMyClass* data = new CMyClass();
FunctionCallingMyCallback( data, &Callback);
delete data;
Now, if I understand you correctly, you need to also pass a char*.
You can either wrap both in a struct and unwrap it in the callback like so:
MyStruct* data = new MyStruct();
data->PtrToMyClass = new CMyClass();
data->MyCharPtr = "test";
FunctionCallingMyCallback( data, &Callback);
delete data->PtrToMyClass;
delete data;
void Callback( void* data)
{
MyStruct *myStructInstance = static_cast<MyStruct *>(data);
CMyClass *myClassInstance = myStructInstance->PtrToMyClass;
char * myData = myStructInstance->MyCharPtr;
myClassInstance->MyInstanceMethod(myData);
}
or, if you can modify the definition of CMyClass, put all the necessary data in class members, so that you can use a callback as in the first example.
If your instance is a singleton (usually implemented using a private or protected constructor and a static pointer to itself) you can do e.g.:
class MyClass {
private:
MyClass():myInstance(0) {}
MyClass *myInstance;
void callback();
public:
~MyClass() {}
static MyClass *getInstance();
static void myCallback();
};
MyClass *MyClass::getInstance() {
if(!myInstance) {
myInstance = new MyClass;
}
return myInsance;
}
void MyClass::callback() {
// non-static callback
}
void MyClass::myCallback() {
getInstance()->callback();
}
If you don't use a singleton but you can pass the instance cast to a void * then you can do this instead:
void MyClass::myCallback(void *data) {
MyClass *instance = static_cast<MyClass *>(data);
instance->callback();
}
This is the only way :
#include <iostream>
#include <cassert>
struct A;
A *oneObj = NULL;
struct A
{
A(){
oneObj=this;
}
~A(){
oneObj=NULL;
}
void foo()
{
}
static void boo()
{
assert( NULL != oneObj );
oneObj->foo();
}
};
int main()
{
A onlyOne;
A::boo();
}
I need to call a non static member function from a static member
function of the same class. The static function is a callback. It can
receive only void as data, though which i pass a char*.
This shows that present design is flawed or inproper. IMHO, you should rather think of changing the design. Just imagine if you somehow get the things working but what about the maintainability an readability of the code.
I would suggest that you should change your callback function to different signature and made according changes.
class A {
//...
static void CallBack (A *pObj)
{
// logic
}
};