shared_ptr reference conversion and const oddity
Here's the test case... class A { public: A() {} virtual ~A() {} }; class B : public A { public: B() {} }; class X1 { public: X1(const boost::shared_ptr<A>& a) {} virtual ~X1() {} }; class Y1 : public X1 { public: Y1(const boost::shared_ptr<B>& b) : X1(b) {} }; class X2 { public: X2(boost::shared_ptr<A>& a) {} virtual ~X2() {} }; class Y2 : public X2 { public: Y2(boost::shared_ptr<B>& b) : X2(b) {} }; int main(int argc, char** argv) { boost::shared_ptr<B> b(new B()); Y1 y1(b); // ptr const in constructor, compiler ok Y2 y2(b); // ptr not const in constructor, compiler not ok } My question is why conversion of the shared_ptr reference does not work if it is not declared const? Here's the compiler error (gcc 3.4.4 - cygming special)... compiling main.cpp... main.cpp: In constructor `Y2::Y2(boost::shared_ptr<B>&)': main.cpp:31: error: no matching function for call to `X2::X2(boost::shared_ptr<B>&)' main.cpp:23: note: candidates are: X2::X2(const X2&) main.cpp:25: note: X2::X2(boost::shared_ptr<A>&) make: *** [obj/main.o] Error 1 Thanks, Brian
Brian Hassink wrote:
My question is why conversion of the shared_ptr reference does not work if it is not declared const?
A non-const reference doesn't bind to temporaries, it needs to bind directly to the argument (this a bit oversimplified but correct for our case). So the shared_ptr<B> argument is not converted to a temporary shared_ptr<A> in the non-const case.
participants (2)
-
Brian Hassink
-
Peter Dimov