这是一个聪明的指针
Is this a smart pointer?
请看下面的代码。这是一个聪明的指针吗?如果是这样,为什么第一个对象 p1 在代码末尾悬空?(也就是说 p2 被析构函数删除,但 p1 仍然存在,为什么?
#include <iostream>
#include <vector>
using namespace std;
template <class T> class my_auto_ptr {
T* myptr;
public:
my_auto_ptr(T* ptr = 0) : myptr(ptr) { }
~my_auto_ptr() {
delete myptr;
}
T* operator ->() const {
if (myptr != nullptr) return myptr;
else throw runtime_error("");
}
T& operator* () const {
if (myptr != nullptr) return *myptr;
else throw runtime_error("");
}
T* release() {
T* rptr = myptr;
myptr = 0;
return rptr;
}
};
//----------------------------------
int main() try {
my_auto_ptr<vector<int> > p1(new vector<int>(4, 5));
cout << p1->size() << endl;
my_auto_ptr<int> p2(new int(6));
cout << *p2 << endl;
return 0;
}
//-------------------------------
catch (...) {
cerr << "Exception occurred.n";
return 1;
}
这是一个聪明的指针吗?
不。它是可复制和可分配的,但执行其中任一操作都会导致多次删除。您需要确保它是不可复制和不可分配的,或者它实现了 3 或 5 的规则。
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 引用一个已擦除类型(void*)的指针
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 不明白迭代器,引用和指针失效,一个例子
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 将指针分配给另一个指针时会发生什么情况?
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++将一个指针分配给另一个指针时执行的类型检查
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 取消引用结束指针到数组类型的一个
- 更改一个指针后更改乘法对象
- const和指针(一个节点示例)
- 从函数返回指针.一个指针的值未更新