Best const ReferenceCountedObjectPtr workflow


#1

Lets say I have classes as follows

class Class : public ReferenceCountedObject
{

public:

    ...

    typedef ReferenceCountedObjectPtr<Class> Ptr;

};


class Data
{

public:

    ...other data...

    Class::Ptr classPtr;

};

I want to do something like this:

1. Construct and fill my Data structure.

2. Pass it to a function. I want to pass it as const to prevent the data being changed.

function (const Data data) { ... }

Passing in const Data (therefore const Class::Ptr doesn't work as ReferenceCountedObjectPtr returns a non-const pointer to the object in a const function.

Is there a good way to const this data structure completely? I could change it to the implementation below, but reformatting all the current code to copy all data into Data in a constructor would be a lot of work.

class Class : public ReferenceCountedObject
{

public:

    ...

    typedef ReferenceCountedObjectPtr<const Class> Ptr;

};

Any ideas?


#2

Yes, this is a common problem with all kinds of smart pointers. I think that in the standard C++ library for things like unique_ptr and shared_ptr, the general consensus is "leave it non-const don't worry about it".

What you'd need here would be some kind of ConstReferenceCountedObjectPtr class, which I've never added, as it's a bit of an edge-case and causes other complications.

If it's really vital to block people from changing it, why not make the data member private, and have an accessor method that returns the target object as a const reference?