Reputation: 97
I am trying to create smart pointer to my function.
I have the function:
double returnValue(int i){
return i;
}
Its pretty simple to create raw pointer:
double (*somePTR)(int) = &returnValue;
But how to make smart pointer to the function, for example shared_ptr
?
auto someptr = std::make_shared<double>(&returnValue);
I have tried a lot of of options, but nothing works.
Upvotes: 5
Views: 3429
Reputation: 5069
I think you mean a smart function pointer, and for that there is since C++11, std::function
, so how about this:
#include <functional>
#include <iostream>
double a(int i){
return i;
}
double b(int i){
return i * 2;
}
double c(double d, int i){
return i - d;
}
int main() {
std::function<double(int)> func = a;
std::cout << func(42) << std::endl;//Output 42
func = b;
std::cout << func(42) << std::endl;//Output 84
//func = c; //Error since c has a different signature (need one more argument), #type safety
func = std::bind(c, 5 ,std::placeholders::_1); //func stores the needed 2nd argument
std::cout << func(42) << std::endl;//Output 37
}
Upvotes: 11
Reputation: 1261
Not sure about use-case, maybe it is needed only because of some uniformity in processing.
shared_ptr<>
cannot contain a pointer to function, but can contain a dynamically allocated pointer to pointer to a function:
double f(int i) { return i; }
typedef double(*f_ptr)(int i);
int main (int _argc, char const **_argv) {
std::shared_ptr<f_ptr> s(new f_ptr(f));
(*s)(2); // okay
s.reset(); // releases a pointer to pointer, not function
// ...
}
Upvotes: 0
Reputation: 206747
You cannot. Smart pointers are only for object pointers not function pointers.
The intent behind smart pointers is to manage dynamically allocated memory. If a smart pointer is able to determine the dynamically allocated memory can be deallocated, it does that.
There is no such thing for function pointers.
Upvotes: 5
Reputation: 2135
You simply can not do that. Since you don't do memory management, like allocate dynamic memory or destroy a function when it goes out of scope, for example, it does not make sense to have a smart pointer for that. Have first a look to the intention of smart pointers and when would you use them.
Upvotes: 0
Reputation: 1429
Smart pointers exist to manage the data behind the address.
In case of a function pointer this data is program code. If the pointer runs out of scope it can't just delete the function.
Smart pointers can't hold function addresses because there wouldn't be any reason for them to do so.
Upvotes: 3