boost::shared_ptr and operator->()

D

Derek

Something puzzles me about Boost's shared_ptr implementation:

template <typename T>
class shared_ptr
{
public:
T* operator->() const
{
return p;
}
private:
T* p;
};

Why is operator->() const but the return value is non-const? The
Boost documentation answers this very question as follows:

"Shallow copy pointers, including raw pointers, typically don't
propagate constness. It makes little sense for them to do so, as you
can always obtain a non-const pointer from a const one and then
proceed to modify the object through it."

I don't understand this answer. Are they referring to using
const_cast to subvert the constness of shallow copy pointers? If so,
that seems like a weak argument for not enforcing const corectness.

Any insights appreciated.
 
R

Rob Williscroft

Derek wrote in
Something puzzles me about Boost's shared_ptr implementation:

template <typename T>
class shared_ptr
{
public:
T* operator->() const
{
return p;
}
private:
T* p;
};

Why is operator->() const but the return value is non-const? The
Boost documentation answers this very question as follows:

"Shallow copy pointers, including raw pointers, typically don't
propagate constness. It makes little sense for them to do so, as you
can always obtain a non-const pointer from a const one and then
proceed to modify the object through it."

Perhapse this will help (for illustration only), what a shared_ptr would
"look" like when const:

template <typename T>
class shared_ptr_const
{
public:
T* const operator->()
{
return p;
}
private:
T* const p;
};

Note that its T * const p *not* T const *p;

T t;
T *v;
T * const c = &t;
v = c; /* shallow copy ?? (losses toplevel const)*/

The (legal) copy above is the same (in a const-correct sense) as:

int const ic = 2;
int j = ic;

Adding (toplevel) const to a return type (as I did in the
illustration above) is mostly useless.
I don't understand this answer. Are they referring to using
const_cast to subvert the constness of shallow copy pointers? If so,
that seems like a weak argument for not enforcing const corectness.

Nope, that's not what is being discussed.

Rob.
 
D

Derek

Rob, your reply makes perfect sense. I overlooked that a const
shared_ptr's member raw pointer is T* const p, not T const *p. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top