Is this an error in "More Effective C++" in Item28?

Posted by particle128 on Stack Overflow See other posts from Stack Overflow or by particle128
Published on 2013-11-05T03:50:56Z Indexed on 2013/11/05 3:53 UTC
Read the original article Hit count: 147

Filed under:

I encountered a question when I was reading the item28 in More Effective C++ .In this item, the author shows to us that we can use member template in SmartPtr such that the SmartPtr<Cassette> can be converted to SmartPtr<MusicProduct>.
The following code is not the same as in the book,but has the same effect.

#include <iostream>

class Base{};
class Derived:public Base{};

template<typename T>
class smart{
public:
    smart(T* ptr):ptr(ptr){}
    template<typename U>
    operator smart<U>()
    {
        return smart<U>(ptr);
    }
    ~smart(){delete ptr;}
private:
    T* ptr;
};
void test(const smart<Base>& ) {}
int main()
{
smart<Derived> sd(new Derived);
test(sd);
return 0;
}

It indeed can be compiled without compilation error. But when I ran the executable file, I got a core dump. I think that's because the member function of the conversion operator makes a temporary smart, which has a pointer to the same ptr in sd (its type is smart<Derived>). So the delete directive operates twice. What's more, after calling test, we can never use sd any more, since ptr in sd has already been delete.
Now my questions are :

  • Is my thought right? Or my code is not the same as the original code in the book?
  • If my thought is right, is there any method to do this?

Thanks very much for your help.

© Stack Overflow or respective owner

Related posts about c++