C++2.0之前,有个智能指针叫auto_ptr。
->符号作用下去之后,会一直作用下去。
sp->已经作用完了,还能px->吗? 可以的,会一直作用下去,这样子这个设计才有意义。

代码:
template<typename T>
class shared_ptr {
public:
shared_ptr(T* p) : px(p) {}
// 智能指针一定是这种写法,重载 * 和 ->
T& operator*() const{
return *px;
}
T* operator->() const{
return px;
}
private:
T* px;
};
struct Foo {
void method() {
cout << "This is a test." << "\n";
}
};
int main(int argc, char** argv) {
shared_ptr<Foo> sp(new Foo);
sp->method();
system("pause");
return 0;
}
智能指针 C++11 以后有几种,具体需要去查,并且具体用法需要去了解,同时需要去看源码。
迭代器
迭代器也是指针的包装,也可认为是一种智能指针。
本文介绍C++2.0之前的智能指针auto_ptr,并通过代码示例展示了shared_ptr的实现方式及其如何使用。同时探讨了迭代器作为智能指针的一种形式。
140

被折叠的 条评论
为什么被折叠?



