개발/일상
boost shared_from_this() bad_weak_ptr Exception 문제 해결
clucle
2019. 8. 13. 06:36
-- 알게 된 내용 2020.02.28
생성자에서 shared_from_this() 함수를 호출하면 아직 만들어지지 않은 객체에 대해 포인팅 할 수 없어서 에러가 발생하는 것으로 보인다
// works
ClientSession::ClientSession(tcp::socket socket)
: socket_(std::move(socket)), read_msg_(0)
{
}
void ClientSession::start()
{
Login::get_instance().join(shared_from_this());
do_read();
}
// error
ClientSession::ClientSession(tcp::socket socket)
: socket_(std::move(socket)), read_msg_(0)
{
Login::get_instance().join(shared_from_this());
}
void ClientSession::start()
{
do_read();
}
-- 알게 된 내용 2019.11.19
https://stackoverflow.com/questions/22782149/shared-ptr-why-does-it-break
아래 예제에서 에러가 나는 이유는 ptr_con->test(); 를 호출한 시점에서 test 함수에서는 shared_ptr의 소유권을 가지고 있는게 아닌 raw_pointer 의 객체 안에서 함수를 부르기 때문에 에러가 난다. 이를 해결하기 위해서 std::enable_shared_from_this 앞에 public 을 붙임으로서 해결한다.
#include <iostream>
#include <memory>
class Connection : std::enable_shared_from_this<Connection> {
public:
Connection() {};
void test();
};
void Connection::test()
{
std::shared_ptr<Connection> ptr = shared_from_this();
}
int main() {
Connection* con = new Connection();
std::shared_ptr<Connection> ptr_con(con);
ptr_con->test();
return 0;
}
-- 원본 내용
아래 소스에서 Exception: bad_weak_ptr이 발생하였다
void Connection::test()
{
auto self(shared_from_this());
}
아래 처럼 enabled_shared_from_this 앞에 public 을 붙여주지 않아서 발생했던 문제로 해결하였다.
// NO
class Connection : std::enable_shared_from_this<Connection>
// YES
class Connection : public std::enable_shared_from_this<Connection>