bind 할 때 ref 시그니처를 가지는 함수 사용하는 법
아래 코드가 컴파일이 안되면서 문제시작.
boost 의 asio 튜토리얼 3번인데 원래 함수의 시그니처에 포인터로 되어있던 것을 참조로 고치면서 문제발생함
https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/tutorial/tuttimer3/src.html
해결방법: 함수로 전달하는 인자(파라미터) t을 std::ref(t)로 변경하면 됨.
이유: https://stackoverflow.com/questions/33240993/c-difference-between-stdreft-and-t
bind 함수가 실행될 때 인자를 모조리 복사(!)해서 함수자(?확인필요)로 저장해 두었다가 나중에 사용하는데, 이 때 객체의 복사가 발생함. 불행히도 steady_timer는 클래스 정의부분에 "복사 생성자"를 삭제(basic_waitable_timer.hpp line:693 참조)했기 때문에 컴파일 에러가 발생함.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <functional>
using boost::asio::io_context;
using boost::asio::steady_timer;
using boost::asio::chrono::seconds;
using boost::asio::placeholders::error;
using boost::system::error_code;
using std::cout;
using std::endl;
void print(const error_code& /*e*/, steady_timer& t, int& count)
{
if (count < 5)
{
cout << count << endl;
++(count);
t.expires_at(t.expiry() + seconds(1));
// t.async_wait(boost::bind(print, error, t, count)); // 에러
t.async_wait(boost::bind(print, error, std::ref(t), count));
}
}
int main()
{
io_context io;
int count = 0;
steady_timer t(io, seconds(1));
// t.async_wait(boost::bind(print, error, t, count)); // 에러
t.async_wait(boost::bind(print, error, std::ref(t), count));
io.run();
cout << "Final count is " << count << endl;
return 0;
}
참조사이트
1, 2: 본문에 링크
3 : https://pmoncode.tistory.com/23
C++. 복사 생성자와 복사 대입 연산자의 차이
C++. 복사 생성자 (Copy Constructor) 와 복사 대입 연산자 (Copy Assignment Operator) 의 차이 참고 : Effective C++ 처음에 복사 생성자와 복사 대입 연산자를 공부하고 나면, 언제 이 친구들이 호출되는지 어..
pmoncode.tistory.com