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?
The issue is here:
The
Vector
constructor takes an lvalue reference, but increateMember()
you're passing in an rvalue: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:The second issue in your code is:
As Angew points out, you need to inherit from
enable_shared_from_this
publicly.