您的位置:首页 > 其它

可调用对象

2015-08-18 21:13 302 查看
c++中常常可以重载算法(for_each等)或智能指针中一些函数可以用可调用对象重载。

先以unique_ptr来说明

unique_ptr是智能指针的一种,可以独占所指向的对象。

unique_ptr使用直接初始化新式。

unique_ptr<int> p2(new int(42));    //p2指向一个值为42的int


因为unique_ptr独占所指向的对象,因此unique_ptr不支持普通的拷贝或是赋值操作。

unique_ptr<string> p1(new string("str");
unique_ptr<string> p2(p1);  //错误,不支持拷贝
unique_ptr<string> p3;
p3 = p2;


unique_ptr所支持的操作 unique_ptr u1

空unique_ptr,可以指向类型为T的对象,u1会使用delete来释放它的指针;u2会使用一个类型为D的可调用对象来释放它的指针

unique_ptr

unique_ptr<string> p2(p1.release());         //release将p1置为空
unique_ptr<string> p3(new string("Trex"));
//将所有权从p3转移到p2
p2.reset(p3.release());   //reset释放了p2原来指向的内存


release会切断unique_ptr和它原来管理的对象间的联系。release返回的指针将用来初始化另一个指针或是给另一个指针赋值。

p2.release(); //错误:p2不会释放内存,而且我们丢失了指针

auto p = p2.release(); //正确,但是我们必须记得delete(p)

向unique_ptr传递删除器

//p指向一个类型为objT的对象,并使用一个类型为delT的对象释放objT对象

//它会调用一个名为fcn的delT类型对象

unique_ptr

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}


在类中如果想使用一个函数作为可调用对象,这个函数需要为static函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: