Smart pointers of const objets

B

Bolin

Hi all,

A question about smart pointers of constant objects. The problem is to
convert from Ptr<T> to Ptr<const T>. I have look up and seen some
answers to this question, but I guess I am too stupid to understand
and make them work.

E.g. I have read that boost's smart pointers are able to do this
convertion, but the following code doesn't compile (VC++6.0):

--

#include <iostream>
#include <boost/shared_ptr.hpp>

class A
{
int m_i;
public:
A(int i) { m_i = i;}
int getI() const { return m_i;}
};


void foo(boost::shared_ptr<A const> &a)
{
std::cout << a->getI() << std::endl;
}

int main(int argc, char* argv[])
{
boost::shared_ptr<A> a (new A(2));
foo(a);
return 0;
}

--

gives error C2664: Cannot convert from class Ptr<...> to class
Ptr<const...>& .

However, a foo(boost::shared_ptr<A const> a) (without '&') would work.
I have no idea why.

Playing around on my own, it turns out that

--

#include <iostream>

template <class T>
class Ptr
{
T * m_pointer;

public:

Ptr(T *pext) : m_pointer(pext) {};
T* operator->(void) { return m_pointer; }
operator Ptr<const T> & ()
{
return *(static_cast<Ptr<const T>*>(static_cast<void*>(this)));
}
};

struct A
{
typedef double T;
T m_i;
A(T i) { this->setI(i);}
T getI() const { return m_i;}
void setI(T i) { m_i = i;}
};

void foo(Ptr<const A> &a)
{
std::cout << a->getI() << std::endl;
}

int main ()
{
Ptr<A > a = new A(3.14);
foo(a);
return 0;
}

--

would compile. I could live with a yukky double static_cast. But then,
replacing A and foo by

template <class T>
struct AT
{
T m_i;
AT(T i) { this->setI(i);}
T getI() const { return m_i;}
void setI(T i) { m_i = i;}
};

template <class T>
void fooT(Ptr<const AT<T> > &a)
{
std::cout << a->getI() << std::endl;
}

it doesn't work anymore (error C2664).

I would really appreciate if somebody could explain me what is going
on.

So far, the only way I could make things work is having a ConstPtr and
making Ptr derive from ConstPtr, hoping that nobody will ever use a
Ptr<const T>. This last solution is not very pleasing and I am sure
there are better ways, I am just not sure how to do.

Thanks for your time,

Bolin
 
T

tom_usenet

Hi all,

A question about smart pointers of constant objects. The problem is to
convert from Ptr<T> to Ptr<const T>. I have look up and seen some
answers to this question, but I guess I am too stupid to understand
and make them work.

E.g. I have read that boost's smart pointers are able to do this
convertion, but the following code doesn't compile (VC++6.0):

--

#include <iostream>
#include <boost/shared_ptr.hpp>

class A
{
int m_i;
public:
A(int i) { m_i = i;}
int getI() const { return m_i;}
};


void foo(boost::shared_ptr<A const> &a)

void foo(boost::shared_ptr<A const> a)
or
void foo(boost::shared_ptr<A const> const& a)

You shouldn't pass "pointers" by reference though, since it disables
conversions (for reasons that should be fairly obvious).

{
std::cout << a->getI() << std::endl;
}

int main(int argc, char* argv[])
{
boost::shared_ptr<A> a (new A(2));
foo(a);
return 0;
}

--

gives error C2664: Cannot convert from class Ptr<...> to class
Ptr<const...>& .

However, a foo(boost::shared_ptr<A const> a) (without '&') would work.
I have no idea why.

You can't bind a temporary to a non-const reference. Things like
pointers and iterators should not be passed by non-const reference
unless you intend to change the original value. Obviously, to change
the original value, you have to pass an lvalue of the correct type to
the function in question.

E.g. this is similarly illegal code:

void f(int const*& p)
{
}

int main()
{
int* p;
f(p);
}

Why should shared_ptr behave any differently?

Tom
 
B

Bolin

tom_usenet said:
void foo(boost::shared_ptr<A const> a)
or
void foo(boost::shared_ptr<A const> const& a)

You shouldn't pass "pointers" by reference though, since it disables
conversions (for reasons that should be fairly obvious).

I am not sure to get that last sentence -- probably not obvious for
people like me. Plus, I always thought it was a bad idea to pass an
object. A smart smart pointer might contain much more than just a
pointer. Besides, references to pointers are used in boost's examples
illustrating the use of smart pointers (e.g. in
shared_ptr_example.cpp).

You can't bind a temporary to a non-const reference. Things like
pointers and iterators should not be passed by non-const reference
unless you intend to change the original value. Obviously, to change
the original value, you have to pass an lvalue of the correct type to
the function in question.

Is a temporary created when passing by reference? I thought no. A cout
in the class constructor do not produce any output when calling foo(A
&a). Should a temporary be created in theory?

E.g. this is similarly illegal code:

void f(int const*& p)
{
}

int main()
{
int* p;
f(p);
}

Why should shared_ptr behave any differently?

Again, I am not sure what is illegal here. Besides, the code compiles.

Thanks,

Bolin
 
T

tom_usenet

I am not sure to get that last sentence -- probably not obvious for
people like me. Plus, I always thought it was a bad idea to pass an
object. A smart smart pointer might contain much more than just a
pointer. Besides, references to pointers are used in boost's examples
illustrating the use of smart pointers (e.g. in
shared_ptr_example.cpp).

The problem is that you cannot bind a temporary object to a non-const
reference. You can only bind an lvalue (usually a named variable of
the matching type) to a non-const reference. Here we have a variable
of type
shared_ptr<A>
and you are trying to bind it to a reference
shared_ptr<A const>&
Now, there is a conversion from shared_ptr<A> to shared_ptr<A const>,
but this introduces a temporary object, which will not bind to the
non-const reference. It will bind to a const reference though:
shared_ptr<A const> const&
since that conversion isn't considered dangerous since you can't
modify the bound temporary. I can't find anything in the faq about
this unfortunately.
Is a temporary created when passing by reference? I thought no.

For shared_ptr, yes. shared_ptr has a templated copy constructor that
enables the conversions. Your conversion technique is actually
illegal:
operator Ptr<const T> & ()
{
return *(static_cast<Ptr<const T>*>(static_cast<void*>(this)));
}
since you aren't allowed to static (or reinterpret) cast between
unrelated types - Ptr<const T> and Ptr<T> are unrelated types (they
aren't related by inheritence). shared_ptr's (legal) technique is to
add a converting constructor:

template <class U>
shared_ptr(shared_ptr<U> const& other);

That can convert any shared_ptr<T> to any shared_ptr<U> where T*
converts to U*. T* converts to T const* so that is how the conversion
is done, by creating a new shared_ptr<T const>.

A cout
in the class constructor do not produce any output when calling foo(A
&a). Should a temporary be created in theory?

The temporary comes from the conversion. You can of course bind an
object directly to a reference if it is the exact type of a sub type
of the reference type.

ostream& os = cout; //direct binding
shared_ptr<T> p;
shared_ptr<T>& pref = p; //direct binding
shared_ptr said:
Again, I am not sure what is illegal here. Besides, the code compiles.

Not on my standards compliant compilers! What compiler are you using?

MSVC7.1 (strict mode):
extra.cpp(9) : error C2664: 'f' : cannot convert parameter 1 from 'int
*' to 'const int *& '
Conversion loses qualifiers

Comeau C++ 4.3:
"main.cpp", line 9: error: a reference of type "const int *&" (not
const-qualified) cannot be initialized with a value of type
"int *"
f(p);
^
It has always been illegal in standard C++ to bind a temporary (in
this case a temporary int const*) to a non const reference. IIRC, MS
compilers allow the conversion in non-strict mode for backwards
compatibility with their pre-standard C++ compilers.

See e.g.
http://groups.google.com/groups?hl=...-8&[email protected]

Tom
 
T

tom_usenet

Okay, thanks, now I understand. The key here is that to go from ptr<T>
to ptr<T const>, boost's smart pointer is using a constructor, hence a
temporary object is created, of which the compiler should forbid using
a reference. So long for shared_ptr.

There are still two questions in my mind though:
(1) Why is a foo(const ptr*&) illegal?

I've put some reasons below (including a const correctness violation).
(2) Why not using convertion operator rather than constructors to go
from Ptr<T> to Ptr<const T>?

It wouldn't make any difference:

operator Ptr<const T>() const;
introduces a temporary, and
operator Ptr<const T>&() const;
is impossible (or at least difficult or non-portable) to write, since
Ptr<T> and Ptr<const T> are unrelated types. In addition, you have to
specialize for const T, since otherwise you end up creating and
operator T() for a class T, which is of course illegal.
More in details:

(1) I compile your example with VC++6.0, it works even with the STRICT
flag on.

No it doesn't. With /Za I get:
c:\dev\test\vctest\main.cpp(9) : error C2664: 'f' : cannot convert
parameter 1 from 'int *' to 'const int *& '
Conversion loses qualifiers

I think it is normal since no temporary is created there
(contrary to the link you provided, where a conversion is needed).
Actually, I think VC++ does quite an intelligent job, since it _does_
produce an error if foo((const or not)A &a) is called with an object
that requires a temporary to be created, but not in the other cases. I
would assume this is the desired behavior.

However, it violates const correctness, and causes other problems
where you accidently modify the wrong value. e.g.

void f(long& l)
{
++l;
}

int main()
{
int i = 10;
f(i);
//is f 10 or 11?
}

The above is of course illegal on conforming compilers, because of the
reference binding rule.
(2) It seems awkward to have to duplicate an object just to convert
from Ptr<T> to Ptr<const T>. I would assume that no compiler
duplicates a T* when a const T* is needed (which is why I think your
exemple should compile).

Actually, the most compliant compiler I have does create a temporary.
Consider:
#include <iostream>
int main()
{
int* p;
int const* const& pref = p; //requires a temporary int const*
std::cout << &p << ' ' << &pref << '\n';
}

Comeau C++ prints two different numbers (differing by 4
unsurprisingly). My other compilers do print the same value, but I
think that this is strictly speaking illegal.

However, I should demonstrate why the conversion in question is
horribly broken - it violates const correctness. The following
compiles on MSVC6 (without /Za) and breaks const correctness, and yet
no casts have been used:

int const i = 10;

void f(int const*& c)
{
c = &i;
}

int main()
{
int* p = 0;
f(p);
if (p != 0) //this should be true
*p = 5; //modifying const!!!
}

It asserts when run, since the *p=5 attempts to modify read-only
memory. It doesn't compile on conforming compilers which only have
these kinds of problems when casts are improperly employed.

To be more precise, is the double static_cast
really non-compliant?

Yes, you can't static cast (via void*, which is equivalent to a
reinterpret_cast really) between two non-POD types. The layout of the
two objects might be different for a start (though usually isn't).

It is, again, compiling and working just fine by
me (with STRICT also) -- that is, as long as embedded templates are
not used, as I reported in my first post.

Compiling and working on a 5 year old compiler is somewhat different
to being compliant. However, it will generally work, but it has the
same potential const-correctness violation that the MSVC6 pointer
example had, this time achieved using illegal casts.

Tom
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top