我想在C++中使用模板來實現智能指針(基本上是唯一的指針),以便於理解。在C++中使用模板的SmartPointer
這是我已經編寫
using namespace std;
template<typename T>
class smartPointer
{
private:
T *mPtr;
public:
smartPointer(T* init=nullptr):mPtr(init)
{
cout<<"Inside ctr"<<endl;
}
//silence the default ctr
smartPointer() = delete;
//disable copy ctr and copy assignment
smartPointer (const smartPointer& other) = delete;
smartPointer& operator=(const smartPointer& other) = delete;
//implement move ctr and move assignment
smartPointer (smartPointer&& other)
{
cout<<"Inside move ctr "<<endl;
mPtr = other.mPtr;
other.mPtr = nullptr;
}
smartPointer& operator=(smartPointer&& other)
{
cout<<"Inside move = before "<<endl;
if(&other != this)
{
mPtr = other.mPtr;
other.mPtr = nullptr;
cout<<"Inside move = after "<<endl;
}
return *this;
}
//deference
T& operator*()
{
return *mPtr;
}
//arrow access operator
T* operator->()
{
return mPtr;
}
~smartPointer()
{
cout<<"Inside ~dtr"<<endl;
if(mPtr != nullptr)
delete mPtr;
}
};
int main()
{
smartPointer<int> sptr(new int);
// Even smartPointer<int> sptr(new int[20]); too works
*sptr = 10;
cout<<"Value pointed by the pointer is "<<*sptr<<endl;
smartPointer<int> sptr2(new int);
// sptr2 = sptr; // complains as expected
sptr2 = move(sptr); // works well
/*
How to
smartPointer<int[]> sptr(new int[20]);
*/
return 0;
}
如何讓這個智能指針爲智能指針工作?
構建指令I得到是 克++ -std = C++ 11 -smartPointer.cpp -o智能指針
請[刪除'使用命名空間std;'](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)。 – Quentin