std::enable_shared_from_this: no known conversion from a to a

1.7k views Asked by At

I have a class VectorSpace with a member createVector() which creates a Vector with a shared pointer to the referencing VectorSpace. This is achieved by std::enable_shared_from_this.

However, this following code

#include <memory>

class Vector;
class VectorSpace;

class Vector {
public:
  Vector(std::shared_ptr<VectorSpace> & space):
    space_(space)
  {
  };

private:
  std::shared_ptr<VectorSpace> space_;
};

class VectorSpace: std::enable_shared_from_this<VectorSpace> {
  public:
  VectorSpace(){};

  Vector
  createMember()
  {
    return Vector(shared_from_this());
  };

};

int main() {
  auto space = std::make_shared<VectorSpace>();
  Vector x(space);
}

fails with compile with the very strange error message

test.cpp:8:3: note:   no known conversion for argument 1 from ‘std::shared_ptr<VectorSpace>’ to ‘std::shared_ptr<VectorSpace>’

(This is with GCC 4.9.2.)

What's the deal here?

1

There are 1 answers

2
Barry On BEST ANSWER

The issue is here:

Vector(std::shared_ptr<VectorSpace> & space):
                                   ^^^

The Vector constructor takes an lvalue reference, but in createMember() you're passing in an rvalue:

  Vector
  createMember()
  {
    return Vector(shared_from_this());
  };

Just drop the &. For what it's worth, I don't have access to gcc 4.9.2, but on 5.1.0 at least the error message is pretty clear:

main.cpp: In member function 'Vector VectorSpace::createMember()':

main.cpp:24:35: error: invalid initialization of non-const reference of type 'std::shared_ptr<VectorSpace>&' from an rvalue of type 'std::shared_ptr<VectorSpace>'

     return Vector(shared_from_this());    
                                   ^

The second issue in your code is:

class VectorSpace: std::enable_shared_from_this<VectorSpace> {

As Angew points out, you need to inherit from enable_shared_from_this publicly.