【发布时间】:2014-02-15 06:26:42
【问题描述】:
我试图编写一个示例代码来实现共享指针[仅供练习]。 在以下示例中,
- 为什么编译器不抱怨修改
other_T -
为什么没有调用复制构造函数
SharedPtr(const T& other_T)? 这是代码sn-p。#include <iostream> using namespace std; #define DBG cout<<"[DEBUG]"<<__PRETTY_FUNCTION__<<endl class RefCount { protected: int m_ref; RefCount(){ DBG; m_ref = 1 ; } void reference(){ DBG; ++m_ref; } void dereference(){ DBG;--m_ref; } }; template <class T> class SharedPtr : public RefCount { T* m_T; public: SharedPtr() { DBG; m_T = new T; } SharedPtr(const T& other_T){ DBG; m_T = other_T.m_T; other_T.dereference(); other_T.m_T = NULL; } ~SharedPtr() { DBG; dereference(); cout<<m_ref<<endl; if(m_ref <= 0 && m_T != NULL ){ cout<<"Destroying"<<endl; delete m_T; m_T = NULL; } } }; class A{}; int main() { SharedPtr<A> obj; cout<<"assigning "<<endl; SharedPtr<A> obj2 = obj; cout<<"END"<<endl; return 0; }
结果是段错误。
【问题讨论】:
-
一方面,它应该是
SharedPtr(const SharedPtr<T>& other_T)。此外,您的复制构造函数不应该尝试修改other_T。你应该在做任何事情之前测试&other_T是否与this相同。 -
@Apprentice 但不一定非得是
const。还是您只是在说一般建议? -
@remyabel 你为什么删除你的答案?没错。
-
@remyabel,是的,你是对的,它不一定是
const。但它是更好的,如果它不是,通常会是一个惊喜。他的复制构造函数看起来像一个移动而不是一个副本。
标签: c++ templates copy-constructor