【c++20】‘std::allocator<char>::allocate‘: function does not take 2 arguments

这篇博客介绍了C++20中std::allocator::allocate函数的改变,指出从C++20开始,该函数不再接受第二个参数。文章详细解释了函数的参数、返回值、异常情况以及注意事项,并提到了与标准库容器的优化相关的内容。此外,还提供了如何在C++20环境下兼容C++17写法的解决方法。
在C/C++中出现“没有与操作数匹配的 `=` 运算符”错误,通常是因为赋值号两边的类型不兼容。从给出的操作数类型来看,`std::shared_ptr<rclcpp::Subscription<std_msgs::msg::String, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::String, std::allocator<void>>>>` 和 `std::shared_ptr<rclcpp::Subscription<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>>>>` 这两种类型并不相同,所以不能直接使用赋值运算符。 要解决这个问题,需要保证赋值号两边的类型一致。以下是一些可能的解决办法: ### 检查订阅者的创建 确认在创建订阅者时使用的类型是一致的。以下是一个示例代码片段,展示了如何正确创建订阅者: ```cpp #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/string.hpp> class Listener : public rclcpp::Node { public: Listener() : Node("listener") { // 确保订阅者的类型一致 subscription_ = this->create_subscription<std_msgs::msg::String>( "chatter", 10, std::bind(&Listener::topic_callback, this, std::placeholders::_1)); } private: void topic_callback(const std::shared_ptr<std_msgs::msg::String> msg) { RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str()); } rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_; }; int main(int argc, char * argv[]) { rclcpp::init(argc, argv); auto node = std::make_shared<Listener>(); rclcpp::spin(node); rclcpp::shutdown(); return 0; } ``` ### 强制类型转换(谨慎使用) 如果确定这两种类型在语义上是兼容的,可以考虑使用强制类型转换。不过这种方法有风险,因为可能会导致未定义行为。 ```cpp std::shared_ptr<rclcpp::Subscription<std_msgs::msg::String, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::String, std::allocator<void>>>> ptr1; std::shared_ptr<rclcpp::Subscription<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>>>> ptr2; // 谨慎使用强制类型转换 ptr1 = std::static_pointer_cast<rclcpp::Subscription<std_msgs::msg::String, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::String, std::allocator<void>>>>(ptr2); ``` ### 检查代码逻辑 仔细检查代码逻辑,确保在创建和使用订阅者时没有意外的类型错误。可能是在某个地方错误地传入了不同类型的参数,导致订阅者的类型不一致。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等风来不如迎风去

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值