#include <iostream>
template <typename T>
class my_smart_ptr {
T* raw;
unsigned * p_count;
public:
my_smart_ptr(T* t):
raw(t),
p_count (new unsigned(1))
{
}
my_smart_ptr(const my_smart_ptr<T> & p):
raw(p.raw),
p_count(p.p_count)
{
++(*p_count);
}
const my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p)
{
if (p == *this)
{
return *this;
}
raw = p.raw;
--(*p_count);
++(*(p.p_count));
return *this;
}
~my_smart_ptr()
{
--(*p_count);
if (*(p_count) == 0)
{
delete raw;
}
}
};
class A{
public:
A()
{
std::cout<< "A()" << std::endl;
}
~A()
{
std::cout<< "~A()" << std::endl;
}
};
int main()
{
my_smart_ptr<A> a (new A);
return 0;
}发布于 2015-05-10 05:13:52
operator=中有一个错误。当函数返回时,LHS的p_count成员仍然指向旧的p_count。它应该等于RHS的p_count。此外,当计数达到零时,忘记释放旧数据。
const my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p)
{
if (p == *this)
{
return *this;
}
// Keep a copy of the old values.
// Don't change these until the state of the
// object has been made consistent.
unsigned* oldCount = p_count;
T* oldRaw = raw;
// Update the state of the object.
// Making sure to get the local count correct.
raw = p.raw;
p_count = p.p_count; // Without this the use count is incorrect.
++(*(p.p_count));
// Now clean up the old state.
--*oldCount;
if (*oldCount == 0) {
delete oldCount;
delete oldRaw;
}
return *this;
}operator=函数通常返回一个非const引用。毕竟,您只是修改了对象。
my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p) { ... }https://codereview.stackexchange.com/questions/90282
复制相似问题