I have this mediator pattern:
File actor.hpp
#pragma once
#include <memory>
#include "mediator.hpp"
class actor : std::shared_from_this<actor>
{
public:
actor(std::shared_ptr<mediator> mediator) : mediator_(mediator)
{
}
virtual ~actor() = 0;
virtual void changed()
{
mediator_->actor_changed(std::make_shared<actor>(this));
}
private:
std::shared_ptr<mediator> mediator_;
};
File mediator.hpp
#pragma once
#include <memory>
class actor;
class mediator : public std::shared_from_this<mediator>
{
public:
virtual ~mediator() = 0;
virtual void actor_changed(std::shared_ptr<actor> actor) = 0;
}
An implementation of an actor request_handler.hpp
#pragma once
#include "actor.hpp"
class request_handler : public actor
{
public:
request_handler(std::shared_ptr<mediator> mediator) : actor(mediator)
{
}
void handle_request()
{
changed();
}
};
But I get the error message
actor.hpp:16 error: invalid new-expression of abstract class type 'actor'
because I cannot instatiate an abstract class. But what would be the correct way of doing this?
This code:
mediator_->actor_changed(std::make_shared<actor>(this));
is logically equal to:
auto ptr = std::shared_ptr<actor>( new actor( this ) );
mediator_->actor_changed(ptr);
and this is most probably not what you want, so you need to call shared_from_this() instead:
mediator_->actor_changed( this->shared_from_this() );
and class you need to inherit from is called std::enable_shared_from_this not shared_from_this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.