【发布时间】:2021-06-18 15:52:53
【问题描述】:
所以对于我的作业,我不允许使用std::smart_ptr,但是我可以自己实现它并进行任何我想要的更改
这就是我所做的
#ifndef SMART_PTR_H_
#define SMART_PTR_H_
template<class T>
class smart_ptr {
T* data;
public: typedef T element_type;
explicit smart_ptr(T* ptr = NULL)
: data(ptr) {}
~smart_ptr() { delete data; }
T& operator*() const { return *data; }
smart_ptr& operator=(smart_ptr<T>&);
};
template<class T>
smart_ptr<T>& smart_ptr<T>::operator=(smart_ptr<T>& ptr)
{
delete this->data;
T* new_data = new T(*ptr);
this->data =new_data;
return *this;
}
#endif
所以我的问题是,对于这样的代码:
template <class T>
SortedList<T>::SortedList(const SortedList<T>& list):
data(new smart_ptr<T>[list.max_size])
,size(list.size)
,max_size(list.max_size)
{
for (int i = 0; i < size; i++)
{
data[i]=list.data[i];// use of operator= of smart_ptr
}
}
所以如果new 抛出std::bad_alloc
会有内存分配还是 smart_ptr 的析构函数会处理所有事情?
【问题讨论】:
-
为什么你的“排序列表”分配智能指针的动态数组?
-
IF a new threw你问的是两个new中的哪一个? -
@eerorika
new在operator= -
另外,
operator=也应该参考const -
除了一元
operator*之外,您还应该定义operator->以便您的类真正表现为智能指针。
标签: c++ memory smart-pointers bad-alloc