/ walking bear:D / C++ note shared_ptr and enable_shared_from_this

C++ note shared_ptr and enable_shared_from_this

2019-09-25 posted in [筆記]

smart pointer 使用最多的場景應該是 async callback,這也是 asio 最常見的 pattern。

#include <iostream>
#include <memory>
#include <boost/asio.hpp>

class MyTimer : public std::enable_shared_from_this<MyTimer> {
public :
	~MyTimer() { std::cout << "~MyTimer()" << std::endl; }
	MyTimer(boost::asio::io_context& ioc, int c) :
		timer(ioc, std::chrono::seconds(1)), counter(c) {}
	void run() {
		if (counter > 0) {
			std::cout <<  counter-- << std::endl;
			timer.expires_after(std::chrono::seconds(1));
#if 1
			timer.async_wait(std::bind(&MyTimer::run, shared_from_this()));
#else
			auto ptr = shared_from_this();
			timer.async_wait([ptr](boost::system::error_code) {
				ptr->run();
			});
#endif
		}
	}
	static void make_myTimer(boost::asio::io_context& ioc, int c) {
		std::make_shared<MyTimer>(ioc, c)->run();
	}
private :
	boost::asio::steady_timer timer;
	int counter = 0;
};

int main(int argc, char* argv[])
{
	boost::asio::io_context ioc;
	MyTimer::make_myTimer(ioc, 3);
	ioc.run();
	return 0;
}

output:

3
2
1
~MyTimer()

. 基于 Boost Asio 的 C++ 网络编程 . shared_ptr 的輔助類別 enable_shared_from_this . reply_count: 1 get_replies : 1 . 2019-09-25_07:28:47 wkliang class MyTimer : public std::enable_shared_from_this<MyTimer> 其中繼承類別的 publc 很重要,否則會報錯:

terminate called after throwing an instance of 'std::bad_weak_ptr'
  what():  bad_weak_ptr
Aborted (core dumped)

程式用了兩種 callback 寫法,前者 bind() 後者 lamda,用條件編譯分開 .

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll