关于我们自己实现的SharedPtr对象赋值问题

关于我们自己实现的SharedPtr对象赋值问题

我的问题:

如图运行结果(白色部分),在调用 “=”重载函数后,原来 ptr3 所指向的对象 调用了void release(),此时 *countRef 变为 0 所以,接着调用~Test()被销毁,那之后为什么又调用了拷贝构造函数?

我的理解:

因为调用“=”重载函数后返回的是一个临时对象返回给ptr3,接着就会调用拷贝构造函数将这个临时对象拷贝给 ptr3,完成后临时对象被销毁。(思路待验证,谢谢老师!!!!!!!!!!!

	SharedPtr<Test> ptr1(new Test("hello world")); 
	cout << "----------- ptr3 ------------" << endl;
	SharedPtr<Test> ptr3(new Test("ptr3")); 			// 创建一个新的SharedPtr指针
	cout << ptr3.getCountRef() << endl;
	ptr3->show();
	cout << "------- ptr3 = ptr1 ---------" << endl;
	ptr3 = ptr1;										// 将 ptr1 赋值给 ptr3
	cout << ptr3.getCountRef() << endl;
	ptr3->show();
	cout << "----------- END -------------" << endl;

图片描述

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
中年猿叔 2024-04-15 18:19:39
要看一下您的赋值运算符重载函数是如何实现的,是不是在这个函数里面有通过拷贝构造产生对象!
  • 提问者 慕斯卡5526745 #1
    template <typename T>
    class SharedPtr {
    public:
    	//
    	explicit SharedPtr(T *_ptr = NULL):ptr(_ptr), countRef(new long(1))
    	{
    		cout << "explicit SharedPtr(T *_ptr = NULL)" << endl;
    	}
    	//拷贝构造函数
    	SharedPtr(const SharedPtr<T> &other):ptr(other.ptr), countRef(other.countRef)
    	{
    		cout << "SharedPtr(const SharedPtr<T> &other)" << endl;
    		(*countRef) ++;
    	}
    	//赋值重载
    	SharedPtr<T> operator=(const SharedPtr<T> &other)
    	{
    		cout << "SharedPtr<T> operator=(const SharedPtr<T> &other)" << endl;
    		if (this != &other) {
    			this->release();
    			ptr = other.ptr;
    			countRef = other.countRef;
    			(*countRef) ++;
    		}
    		return *this;
    	}
    	~SharedPtr()
    	{
    		cout << "~SharedPtr()" << endl;
    		release();
    	}
    	T &operator*(void)
    	{
    		cout << "T &operator*(void)" << endl;
    		return *ptr;
    	}
    	T *operator->(void)
    	{
    		cout << "T *operator->(void)" << endl;
    		return ptr;
    	}
    	T *getPtr(void)
    	{
    		cout << "T *getPtr(void)" << endl;
    		return ptr;
    	}
    	int getCountRef(void)
    	{
    		cout << "int getCountRef(void) : "; 
    		return *countRef;
    	}
    protected:
    	//释放函数
    	void release(void)
    	{
    		cout << "void release(void)" << endl;
    		(*countRef) --;
    		if (0 == *countRef) {
    			if (ptr != NULL)
    				delete ptr;
    			delete countRef;
    		}
    	}
    private:
    	T *ptr;
    	long *countRef;
    };

    重载函数里并没有调用拷贝构造函数,只是简单的成员变量赋值。

    2024-04-15 18:23:24
  • 中年猿叔 回复 提问者 慕斯卡5526745 #2

    赋值运算符有返回对象哦,产生了临时对象,调用拷贝函数!您自己的理解是对的呢!

    2024-04-18 07:10:09
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师