Search code examples
c++boostconstructorshared-ptrsmart-pointers

Boost Shared Pointer Constructors/Destructors


I'm trying to implement smart pointers in my code. I've created a class to convert a Point to a shared_ptr and I've added a print function for the shared_ptr. In my main, I create an array of shared_ptr of type Shape. When I assign Points to the array, I only see raw constructors/destructors, rather than the shared constructor/destructors. Is this code correct?

Thanks.

#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;    
}

The output looks like the below (the constructor/destructor statements are from the Point/Shape/Array classes themselves, rather than from the code in this source file.

Array constructor call

Shape constructor call (default)

Point constructor call (3.1459,3.1459) ID:41

Point destructor call

Shape destructor call

Array destructor call

I was expecting to see shared_ptr constructor/destructor statements. Is my problem in the P1 code or in my implementation in the main or elsewhere?

Thanks!


Solution

  • You're calling

    my_ShapeArray[0]->Print();
    

    which must be a member function of Shape.

    You are not calling the

    Print();
    

    function which you define in the code given and which is the one using the P1 class.