Search code examples
c++visual-studio-2010boostshared-ptr

What is wrong with my shared_ptr initialization list code?


I have a class that contains a shared_ptr to another class. I am setting the shared_ptr in the class's constructor. When I compile this, I get an error that looks very strange to me. Here's the full code:

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

using namespace std;

class MyClass
{
public:
    int _i;

    MyClass(int arg) : _i(arg) { }
};

class MyClassPtr
{
public:
    boost::shared_ptr<MyClass*> _shptr;

    //constructor using initialization list
    MyClassPtr(boost::shared_ptr<MyClass*> arg) : _shptr(arg) { }
};

int main()
{
    boost::shared_ptr<MyClass> sp(new MyClass(123));

    //error C2664: 'MyClassPtr::MyClassPtr(boost::shared_ptr<T>)' : 
    //  cannot convert parameter 1 
    //  from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'
    MyClassPtr mc(sp); 

    return 0;
}

I don't understand the part of the error message that says "from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'". How do I set the _shptr variable in the MyClassPtr constructor?

I'm using Boost 1.54


Solution

  • One of them is a shared_ptr<MyClass> and one is shared_ptr<MyClass*>

    Presumably the compiler error message tells you that, and you're misreading it.