472,992 Members | 3,390 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,992 software developers and data experts.

Smart pointers of const objets

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
Jul 19 '05 #1
5 5011
On 27 Oct 2003 19:49:36 -0800, ga*******@voila.fr (Bolin) wrote:
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
Jul 19 '05 #2
tom_usenet <to********@hotmail.com> wrote in message news:<1c********************************@4ax.com>. ..

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
Jul 19 '05 #3
On 28 Oct 2003 19:44:42 -0800, ga*******@voila.fr (Bolin) wrote:
tom_usenet <to********@hotmail.com> wrote in message news:<1c********************************@4ax.com>. ..

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).


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.
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.


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 coutin 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<T const>& pcref = p; //illegal, requires a temporary
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=e...i.gabi-soft.fr

Tom
Jul 19 '05 #4
tom_usenet <to********@hotmail.com> wrote in message news:<9b********************************@4ax.com>. ..
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.


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?
(2) Why not using convertion operator rather than constructors to go
from Ptr<T> to Ptr<const T>?

More in details:

(1) I compile your example with VC++6.0, it works even with the STRICT
flag on. 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.

(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). To be more precise, is the double static_cast
really non-compliant? 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.

Thanks

Bolin
Jul 19 '05 #5
On 29 Oct 2003 19:52:48 -0800, ga*******@voila.fr (Bolin) wrote:
tom_usenet <to********@hotmail.com> wrote in message news:<9b********************************@4ax.com>. ..
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.


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_castreally 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 byme (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
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Vijai Kalyan | last post by:
I have been thinking about this and it may have already been thrashed out and hung out to dry as a topic of no more interest but here goes. I found when implementing a smart pointer that the...
6
by: zl2k | last post by:
hi, When I considered about preventing memory leaking, the method came up to my mind is using boost smart pointer if possible (use stl::vector instead of type, use smart pointer whenever declare...
13
by: Protoman | last post by:
Here's a non intrusive reference counting smart pointer class I'm working on; I keep getting a "22 C:\Dev-Cpp\SmrtPtr.hpp ISO C++ forbids declaration of `SmrtPtrDB' with no type" error. Code: ...
92
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers,...
5
by: Bhan | last post by:
what r smart pointers?
33
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the...
3
by: mati-006 | last post by:
Hi, I think the code will be the best way to explain what I mean: #include "arglib/arg_shared.h" class base { public: base() {} virtual ~base() {} };
54
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining...
13
by: Phil Bouchard | last post by:
I am currently writting a smart pointer which is reasonnably stable and I decided supporting allocators for completion because of its increase in efficiency when the same pool used by containers is...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.