• 控制拷贝和资源管理、类指针例子


    13.2控制拷贝和资源管理
    1.如果类的每个对象相互独立,不共享除静态成员以外的元素,那么称之为类值的;如果如果类的每个对象不是相互独立,共享了除静态成员以外的元素,那么称之为类指针的。
    2.大多数赋值运算符组合了析构函数函数拷贝构造函数的工作,赋值运算符还必须考虑自赋值的正确性。
    3.类指针的类最好是用shared_ptr来管理类中的资源,否则需要自行定义一个引用计数,将计数器保存在动态内存中
    下面是一个类指针的程序例子:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class hasptr {
    	friend void swap(hasptr&, hasptr&);
    public:
    	hasptr(const string &s = string()) :
    		ps(new string(s)), i(0), use(new size_t(1)) { }
    	hasptr(const hasptr &p) :
    		ps(p.ps), i(p.i), use(p.use) 
    	{
    		++*use;
    	}
    	hasptr& operator = (const hasptr&);
    	hasptr& operator = (const string &);
    	string& operator*();
    	~hasptr();
    
    private:
    	string *ps;
    	int i;
    	size_t *use;
    };
    
    hasptr::~hasptr()
    {
    	if (--*use == 0)		//每销毁一个对象,就将其use指针指向的内存内容减一
    	{
    		delete ps;
    		delete use;
    	}
    }
    
    hasptr& hasptr::operator = (const hasptr &rhs)
    {
    	++*rhs.use;
    	if (--*use == 0)
    	{
    		delete ps;
    		delete use;
    	}
    	ps = rhs.ps;
    	i = rhs.i;
    	use = rhs.use;
    	return *this;
    }
    
    hasptr& hasptr::operator = (const string & rhs)
    {
    	*ps = rhs;
    	return *this;
    }
    
    string & hasptr::operator *()
    {
    	return *ps;
    }
    
    inline void swap(hasptr& lhs, hasptr& rhs)
    {
    	using std::swap;
    	swap(lhs.ps, rhs.ps);
    	swap(lhs.i, rhs.i);
    }
    
    int main(int argc, char*argv[])
    {
    	hasptr h("hi mom");
    	hasptr h2 = h;
    	h = "hi dad";
    	cout << "h: " << *h << endl;
    	cout << "h2: " << *h2 << endl;
    
    	return 0;
    }     
    

      

  • 相关阅读:
    Linux
    Linux
    Linux
    Linux
    Linux
    shell tr命令
    grep 正则表达
    shell 运算符
    shell 重定向
    bzoj 1026 DP,数位统计
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/9412348.html
Copyright © 2020-2023  润新知