我正在尝试创建指向我的函数的智能指针.
我有这个功能:
double returnValue(int i){
return i;
}
Run Code Online (Sandbox Code Playgroud)
创建原始指针非常简单:
double (*somePTR)(int) = &returnValue;
Run Code Online (Sandbox Code Playgroud)
但是,如何制作智能指针,例如shared_ptr
?
auto someptr = std::make_shared<double>(&returnValue);
Run Code Online (Sandbox Code Playgroud)
我尝试了很多选项,但没有任何效果.
我认为你的意思是一个智能函数指针,为此,从C++ 11开始std::function
,那么这个怎么样:
#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
}
Run Code Online (Sandbox Code Playgroud)
你不能。智能指针仅适用于对象指针,不适用于函数指针。
智能指针背后的目的是管理动态分配的内存。如果智能指针能够确定动态分配的内存可以被释放,它就会这样做。
函数指针不存在这样的东西。