#include <string>
#include <cstddef>
#include "hasptr.h"
using namespace std;
HasPtr::HasPtr(const std::string &s):
ps(new std::string(s)), i(0), use(new std::size_t(1)) {}
// copy constructor copies all three data members
// and increments the counter
HasPtr::HasPtr(const HasPtr &p):
ps(p.ps), i(p.i), use(p.use) { ++*use; }
HasPtr::HasPtr(HasPtr &&p): ps(p.ps), i(p.i), use(p.use)
{ p.ps = 0; p.use = 0; }
HasPtr::~HasPtr()
{
if (--*use == 0) { // if the reference count goes to 0
delete ps; // delete the string
delete use; // and the counter
}
}
HasPtr &
HasPtr::operator=(HasPtr &&rhs)
{
if (this != &rhs) {
if (--*use == 0) { // do the work of the destructor
delete ps;
delete use;
}
ps = rhs.ps; // do the work of the move constructor
i = rhs.i;
use = rhs.use;
ps = 0; use = 0;
}
return *this;
}
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
++*rhs.use; // increment the use count of the right-hand operand
if (--*use == 0) { // then decrement this object's counter
delete ps; // if no other users
delete use; // free this object's allocated members
}
ps = rhs.ps; // copy data from rhs into this object
i = rhs.i;
use = rhs.use;
return *this; // return this object
}
HasPtr f(HasPtr hp) // HasPtr passed by value, so it is copied
{
HasPtr ret;
ret = hp; // assignment copies the given HasPtr
// proces ret
return ret; // ret and hp are destroyed
}
//hasptr.h
#include <string>
#include <iostream>
#include <new>
using namespace std;
class HasPtr{
public:
HasPtr(const string &s = string());
HasPtr(const HasPtr &);
HasPtr& operator=(const HasPtr &);
HasPtr(HasPtr &&);
HasPtr& operator=(HasPtr &&);
~HasPtr();
size_t use_count()const
{
cout <<"use_count:" << *use << endl;
return *use;
}
private:
size_t * use;
string * ps;
int i;
};
#include <string>
#include <new>
#include <iostream>
#include "hasptr.h"
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
HasPtr h1("hasptr1");
HasPtr h2;
h2 = (h1);
return 0;
}
编译没问题,运行后出现
Segment fault(cole dumped)
问题已经找到了,是因为变量多次释放造成的。两个赋值运算符指针释放后都佳nullptr,然后
析构函数里面首先判断下 !use是否有值,这样就安全了。
|