我是C ++的新手,在编写实现智能指针的代码时遇到了这个问题并且有些困惑。
template<typename T> class SP
{
T* pData;
public:
SP(T* pValue) : pData(pValue)
{
// pValue = pData;
}
T& operator*()
{
return *pData;
}
T* operator->()
{
return pData;
}
};
class Shape
{
float length;
float breadth;
float area;
public:
Shape()
{ }
Shape(float i,float j)
{
length = i;
breadth = j;
cout<<"Constructor called\n";
cout<<length<<breadth<<endl;
}
void calculateArea()
{
area = length * breadth;
}
void display()
{
cout<<"Lenght = "<<length<<endl;
cout<<"Breadth = "<<breadth<<endl;
cout<<"Area = "<<area<<endl;
}
};
int main()
{
SP<Shape> ptr(new Shape(1.1,2.2));
ptr->calculateArea();
ptr->display();
return 0;
}
如果我直接分配pValue = pData;
我看到内存故障,就像使用初始化程序时程序运行正常。
SP(T* pValue) : pData(pValue)
请帮助我了解使用初始化列表时编程是如何正常运行的。
答案 0 :(得分:2)
你已经交换了作业。
而不是
pValue = pData;
你想做
pData = pValue;