我想在我的代码中实现智能指针。我创建了一个类将Point转换为shared_ptr,并且为shared_ptr添加了一个打印函数。在我的主要中,我创建了一个Shape类型的shared_ptr数组。当我将Points指定给数组时,我只能看到原始的构造函数/析构函数,而不是共享的构造函数/析构函数。这段代码是否正确?提升共享指针构造函数/析构函数
谢谢。
#include "Point_H.hpp"
#include "Shape_H.hpp"
#include "Array_H.hpp"
#include "boost/shared_ptr.hpp"
using namespace CLARK::Containers;
using namespace CLARK::CAD;
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 << endl; }
};
void Print()
{
boost::shared_ptr<Point> myPoint (new Point);
{
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);
ShapePtr my_Point (new Point(3.1459, 3.1459));
my_ShapeArray[0] = my_Point;
my_ShapeArray[0]->Print();
return 0;
}
输出看起来像下面(的构造/析构语句是从点/形状/阵列类本身,而不是从在该源文件中的代码。
Array构造调用
形状构造函数调用(默认)
点构造函数调用(3.1459,3.1459)ID:41
点析构函数调用
形状析构函数调用
阵列析构函数调用
我期待看到shared_ptr的构造函数/析构函数语句。我的问题在P1代码中还是在我的主要或其他地方执行?
谢谢!
'shared_ptr'不是一个通用的解决方案。事实上,这几乎总是错误的解决方案。如果数组拥有对象,并且其他函数仅在数组中包含对象时才使用对象,则使用“unique_ptr”集合,然后将原始指针(或引用)传递给其他函数。 –
你实际上可能想要一个ptr_vector和来自http://www.boost.org/doc/libs/1_51_0/libs/ptr_container/doc/ptr_container.html – Soverman