【发布时间】:2021-11-06 09:24:02
【问题描述】:
这段代码编译正确。
#include <asio.hpp>
#include <memory>
#include <iostream>
struct Message { int msg; };
// never mind global variables, just for the sake of making this a minimal example
extern asio::ip::tcp::socket mysocket;
void handler(std::shared_ptr<Message> pmsg, asio::error_code error, size_t nbytes);
void readMessage()
{
std::shared_ptr<Message> pmsg{ new Message };
asio::async_read(mysocket, asio::buffer(&pmsg->msg, sizeof(int)),
[pmsg](auto err, auto nbytes) { handler(pmsg, err, nbytes); });
}
但是,当我添加对处理函数的第一个参数的引用时
void handler(std::shared_ptr<Message>& pmsg, asio::error_code error, size_t nbytes);
代码不再编译,抱怨我试图将 pmsg 从 const std::shared_ptr<Message>& 转换为 std::shared_ptr<Message>&。
要让它再次工作,我必须在对处理程序的调用中引入const_cast<std::shared_ptr<Message>&>。
const-ness 是在哪里引入的?
谢谢
【问题讨论】: