拷贝控制和资源管理

假定我们希望HasPtr的行为像一个值。即,对于对象所指向的string成员,每个对象都有一份自己的拷贝。

#include<stdio.h>
#include<iostream>
#include<vector>
#include<string>

using namespace std;

class HasPtr {
public:
    HasPtr(const string &s=string()):
        ps(new string(s)),i(0) { }
    HasPtr(const HasPtr &p):
        ps(new string(*p.ps)),i(p.i) { }
    HasPtr& operator=(const HasPtr&);
    HasPtr& operator=(const string&);
    string& operator*();
    ~HasPtr();
private:
    string *ps;
    int i;
};

HasPtr::~HasPtr()
{
    delete ps;
}

inline 
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
    auto newps = new string(*rhs.ps);
    delete ps;
    ps = newps;
    i = rhs.i;
    return *this;
}

HasPtr& HasPtr::operator=(const string &rhs) {
    *ps = rhs;
    return *this;
}

string& HasPtr::operator*() {
    return *ps;
}

int main()
{
    HasPtr h("hi mom!");
    HasPtr h2(h);
    HasPtr h3 = h;
    h2 = "hi dad!";
    h3 = "hi son!";
    cout << "h: " << *h << endl;
    cout << "h2: " << *h2 << endl;
    cout << "h3: " << *h3 << endl;
    return 0;
}

输出结果

猜你喜欢

转载自www.cnblogs.com/Summer-8918/p/10245294.html
今日推荐