#include <iostream>
#include <memory>
#include <iostream>
#include <string>
#include <functional>
class client:public std::enable_shared_from_this<client>
{
using CallBack =std::function<void(std::string&&)> ;
public:
client(const CallBack& msg)
:msg_cb_(msg){
}
~client() {
std::cout << "~client()" << std::endl;
}
void display()
{
std::string str = "client";
msg_cb_(std::move(str));
}
private:
CallBack msg_cb_{};
};
class server :public std::enable_shared_from_this<server>
{
using CallBack = std::function<void(std::string&&)>;
public:
server()
{
std::cout << "server()" << std::endl;
}
~server()
{
std::cout << "~server()" << std::endl;
}
void set_init()
{
init_conn_callback();
}
void display()
{
client_->display();
}
private:
void init_conn_callback()
{
//内存泄漏
//msg_cb_ = [self = shared_from_this()](std::string&& msg){
// std::cout << msg << std::endl;
//};
//解决内存泄漏办法
msg_cb_ = [self = this->weak_self()](std::string&& msg){
std::cout << msg << std::endl;
};
client_ = std::make_shared<client>(msg_cb_);
}
std::weak_ptr<server> weak_self() {
return std::weak_ptr<server>(shared_from_this());
}
private:
std::shared_ptr<client>client_{};
CallBack msg_cb_{};
};
int main()
{
auto ptr = std::make_shared<server>();
ptr->set_init();
ptr->display();
}