[英]shared_from_this causing bad_weak_ptr
我正在尝试在 asio 中保留已连接客户端的列表。 我已经从文档( http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/example/cpp03/chat/chat_server.cpp )中改编了聊天服务器示例,这是重要的部分我结束了:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <set>
using boost::asio::ip::tcp;
class tcp_connection;
std::set<boost::shared_ptr<tcp_connection>> clients;
void add_client(boost::shared_ptr<tcp_connection> client)
{
clients.insert(client);
}
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
tcp_connection(boost::asio::io_service& io_service) : socket_(io_service)
{
}
tcp::socket socket_;
void start()
{
add_client(shared_from_this());
}
tcp::socket& socket()
{
return socket_;
}
};
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), 6767))
{
tcp_connection* new_connection = new tcp_connection(io_service_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::start_accept, this, new_connection,
boost::asio::placeholders::error));
}
private:
void start_accept(tcp_connection* new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
new_connection = new tcp_connection(io_service_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::start_accept, this, new_connection,
boost::asio::placeholders::error));
}
}
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
在调用shared_from_this()
时,我的服务器崩溃并显示消息:
异常:tr1::bad_weak_ptr
我做了一些搜索,看起来shared_from_this()
非常特别,但我似乎无法找到我需要更改的确切内容。
约翰·兹温克 (John Zwinck) 的基本分析指出:
错误是您在没有 shared_ptr 指向它的对象上使用 shared_from_this() 。 这违反了 shared_from_this() 的先决条件,即至少必须已经创建(并且仍然存在)一个指向 this 的 shared_ptr。
然而,他的建议在 Asio 代码中似乎完全离题且危险。
您应该通过 - 实际上 - 首先不处理指向tcp_connection
原始指针,而是始终使用shared_ptr
来解决此问题。
boost::bind
有一个很棒的特性,它绑定到shared_ptr<>
就好了,所以只要一些异步操作正在它上面运行,它就会自动保持指向的对象处于活动状态。
这 - 在您的示例代码中 - 意味着您不需要clients
向量,与约翰的回答相反:
void start_accept()
{
tcp_connection::sptr new_connection = boost::make_shared<tcp_connection>(io_service_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(
&tcp_server::handle_accept,
this, new_connection, asio::placeholders::error
)
);
}
void handle_accept(tcp_connection::sptr client, boost::system::error_code const& error)
{
if (!error)
{
client->start();
start_accept();
}
}
我已经包含了一个示例,它使tcp_connection
做一些琐碎的工作(它每秒循环向客户端写入“hello world”,直到客户端断开连接。当它这样做时,您可以看到正在运行的tcp_connection
操作的析构函数:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
namespace asio = boost::asio;
using asio::ip::tcp;
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> sptr;
tcp_connection(asio::io_service& io_service) : socket_(io_service), timer_(io_service)
{
}
void start()
{
std::cout << "Created tcp_connection session\n";
// post some work bound to this object; if you don't, the client gets
// 'garbage collected' as the ref count goes to zero
do_hello();
}
~tcp_connection() {
std::cout << "Destroyed tcp_connection\n";
}
tcp::socket& socket()
{
return socket_;
}
private:
tcp::socket socket_;
asio::deadline_timer timer_;
void do_hello(boost::system::error_code const& ec = {}) {
if (!ec) {
asio::async_write(socket_, asio::buffer("Hello world\n"),
boost::bind(&tcp_connection::handle_written, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred)
);
}
}
void handle_written(boost::system::error_code const& ec, size_t /*bytes_transferred*/) {
if (!ec) {
timer_.expires_from_now(boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&tcp_connection::do_hello, shared_from_this(), asio::placeholders::error));
}
}
};
class tcp_server
{
public:
tcp_server(asio::io_service& io_service)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), 6767))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::sptr new_connection = boost::make_shared<tcp_connection>(io_service_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(
&tcp_server::handle_accept,
this, new_connection, asio::placeholders::error
)
);
}
void handle_accept(tcp_connection::sptr client, boost::system::error_code const& error)
{
if (!error)
{
client->start();
start_accept();
}
}
asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main()
{
try
{
asio::io_service io_service;
tcp_server server(io_service);
boost::thread(boost::bind(&asio::io_service::run, &io_service)).detach();
boost::this_thread::sleep_for(boost::chrono::seconds(4));
io_service.stop();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
典型输出:
sehe@desktop:/tmp$ time (./test& (for a in {1..4}; do nc 127.0.0.1 6767& done | nl&); sleep 2; killall nc; wait)
Created tcp_connection session
Created tcp_connection session
1 Hello world
Created tcp_connection session
2 Hello world
Created tcp_connection session
3 Hello world
4 Hello world
5 Hello world
6 Hello world
7 Hello world
8 Hello world
9 Hello world
10 Hello world
11 Hello world
12 Hello world
13
Destroyed tcp_connection
Destroyed tcp_connection
Destroyed tcp_connection
Destroyed tcp_connection
Destroyed tcp_connection
real 0m4.003s
user 0m0.000s
sys 0m0.015s
错误是您在没有shared_ptr
指向它的对象上使用shared_from_this()
。 这违反了shared_from_this()
的先决条件,即必须已经创建(并且仍然存在)至少一个shared_ptr
指向this
。
您遇到麻烦的根本原因似乎是您最初将new
的结果存储在原始指针中。 您应该将new
的结果存储在智能指针中(基本上总是如此)。 也许您可以立即将智能指针存储在您的clients
列表中。
我在评论中提到的另一种方法是完全停止使用shared_from_this()
。 你不需要它。 至于你提到的这段代码:
if ((boost::asio::error::eof == ec) || (boost::asio::error::connection_reset == ec))
{
clients.erase(shared_from_this());
}
您可以将其替换为:
if ((boost::asio::error::eof == ec) || (boost::asio::error::connection_reset == ec))
{
boost::shared_ptr<tcp_connection> victim(this, boost::serialization::null_deleter());
clients.erase(victim);
}
也就是说,创建一个永远不会解除分配的“哑巴”智能指针( https://stackoverflow.com/a/5233034/4323 ),但它将为您提供从客户端列表中删除它所需的内容。 还有其他方法可以做到这一点,例如通过使用比较函数搜索std::set
,该比较函数采用一个shared_ptr
和一个原始指针,并知道比较它们指向的地址。 您选择哪种方式并不重要,但您可以完全避免shared_from_this()
情况。
// Do not forget to ----v---- publicly inherit :)
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
这里的答案很好,揭示了我的问题的解决方案。 然而,
鉴于这两点,我认为发布有关根本问题的 MRE 以及修复它所需的内容可能会有所帮助。 此代码来自cppreference :
#include <iostream>
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main()
{
try
{
Foo *f = new Foo;
// Oops! this throws std::bad_weak_ptr. f is a raw pointer to Foo (not
// managed by a shared pointer), and calling getFoo tries to create a
// shared_ptr from the internal weak_ptr. The internal weak_ptr is nullptr,
// so this cannot be done, and the exception is thrown. Note, the
// cppreference link above says that prior to C++17, trying to do this
// is undefined behavior. However, in my testing on godbolt, an exception
// is thrown for C++11, 14, and 17 with gcc.
std::shared_ptr<Foo> sp = f->getFoo();
}
catch(const std::bad_weak_ptr& bwp)
{
// the exception is caught, and "bad_weak_ptr" is printed to stdout
std::cout << bwp.what();
exit(-1);
}
return 0;
}
Output:
Foo::Foo
bad_weak_ptr
确保f
由 shared_ptr 管理:
try
{
Foo *f = new Foo;
// this time, introduce a shared pointer
std::shared_ptr<Foo> sp(f);
// now, f is managed by a shared pointer. Its internal weak_ptr is valid,
// and so the retrieval of a shared_ptr via shared_from_this works as
// desired. We can get a weak_ptr or a shared_ptr
std::weak_ptr<Foo> wp = f->getFoo();
std::shared_ptr<Foo> sp2 = f->getFoo();
// all pointers go out of scope and the Foo object is deleted once
// the reference count reaches 0
}
catch(const std::bad_weak_ptr& bwp)
{
std::cout << bwp.what();
exit(-1);
}
Output:
Foo::Foo
Foo::~Foo
正如其他答案 state 和如上所述,在调用shared_from_this
之前,您必须有一个由共享指针管理的 object ,否则您将获得bad_weak_ptr
异常或 UB,具体取决于您的 C++ 标准。 这是任何感兴趣的人的游乐场。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.