首页 > 解决方案 > 将 const 字符串传递给函数 c++ 时出现意外行为

问题描述

const string将a 作为参数传递给函数时,我得到了一个意外的行为。

我有这个功能:

std::string getStatusByTopic(const std::string topic){
    if (topic.compare(TOPIC_WP_SM_CMD) == 0)
            return state_to_string(STATUSES::WP_HANDLER_STATUS);
}

这还没有完全实现。

我有这个功能:

InsertStatus(getStatusByTopic(TOPIC_WP_SM_CMD),msg);

其中声明为:

void Msp::InsertStatus(const std::string status_topic, const std_msgs::String::ConstPtr& new_status)

我有两个问题:

  1. 这些函数已成功编译,即使getStatusByTopic()当其定义的返回类型为string时,可能不返回任何内容。这怎么可能?

  2. 当代码被执行时,场景是并且getStatusByTopic(TOPIC_WP_SM_CMD)什么都不返回。没有运行时错误,更重要的是 - TOPIC_WP_SM_CMD作为参数传递给InsertStatus()(定义为广告“/some/topic/”)。哇,这可能吗?

谢谢。

标签: c++stringcompiler-errors

解决方案


推荐阅读