我仍在尝试在我为家庭作业创建的项目中实现 boost shared_ptr,并不断遇到不同的错误。目前,我觉得我的代码非常接近正确,并且构建良好,但我遇到了一个令人讨厌的运行时错误。我只是想在下面的 MyPrint 函数中访问我的 Shape 类和 Point 类 ToString 函数。
我的代码如下:
#include "Point_H.hpp"
#include "Shape_H.hpp"
#include "Array_H.hpp"
#include "ArrayException_H.hpp"
#include "boost/shared_ptr.hpp"
using namespace CLARK::Containers;
using namespace CLARK::CAD;
class S1
{
private:
boost::shared_ptr<Shape> sp;
public:
S1(boost::shared_ptr<Shape> value) : sp(value) { cout << "S1 constructor call (default)" << endl; }
virtual ~S1() { cout << "S1 destructor call" << endl; }
virtual void print() const { cout << "Shape: " << (*sp).ToString() << endl; }
};
class P1
{
private:
boost::shared_ptr<Point> pp;
public:
P1(boost::shared_ptr<Point> value) : pp(value) { cout << "P1 constructor call (default)" << endl; }
virtual ~P1() { cout << "P1 destructor call" << endl; }
void print() const { cout << "Point: " << (*pp).ToString() << endl; }
};
void MyPrint()
{
{
boost::shared_ptr<Shape> myShape;
{
S1 Shape1(myShape);
Shape1.print();
}
boost::shared_ptr<Point> myPoint;
{
P1 Point1(myPoint);
Point1.print();
}
}
}
int main()
{
// Typedef for a shared pointer to shape
// a typedef for an array with shapes stored as shared pointers.
typedef boost::shared_ptr<Shape> ShapePtr;
typedef Array<ShapePtr> ShapeArray;
ShapeArray my_ShapeArray(3);
my_ShapeArray[0] = ShapePtr (new Point(1,2));
MyPrint();
try
{
cout << my_ShapeArray[0]->ToString() << endl;
return 0;
}
catch(ArrayException& err)
{
cout << err.GetMessage() << endl;
}
}
命令窗口显示以下内容,运行时错误中止程序:
数组构造函数调用
S1 构造函数调用(默认)
断言失败:px != 0,文件 c:\program files x86)\boost\boost_1_51_0\boost\smart_ptr\shared_ptr.hpp,第 418 行
有人可以帮我吗?我已经尝试调试了好几个小时!
*编辑:
每个请求,数组默认构造函数:
数组默认构造函数:
template <typename Type> class Array
{
private:
Type* m_data; // dynamic array of Type objects
int m_size; // size of array
...
};
template <typename Type>
int Array<Type>::m_default_size = 10;
template <typename Type>
Array<Type>::Array()
{// Default constructor
m_size = m_default_size;
m_data = new Type[m_default_size];
cout << "Array constructor call (default)" << endl;
}
谢谢。