You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GDB中向C++的std::string参数函数传递字符串?

在GDB中调用接收std::string参数的函数的方法

问题场景

你有如下两个C++函数:

test函数(接收std::string参数)

bool test(std::string input)
{
  // do something with input
}

test2函数(接收const char*参数)

bool test2(const char* input)
{
  // do something with input
}

调用test2时,执行GDB命令:

(gdb) call test2("test")

可以正常工作,但调用test时执行:

(gdb) call test("test")

却报错:Cannot resolve function test to any overloaded instance。

解决方法

因为GDB不会自动将C风格字符串字面量隐式转换为std::string,所以需要显式构造std::string对象作为参数:

方法1:显式构造std::string

执行如下GDB命令即可正常调用:

(gdb) call test(std::string("test"))

方法2:使用C++11字符串字面量(可选)

如果你的代码支持C++11及以上标准,且启用了字符串字面量特性,也可以使用:

(gdb) call test("test"s)

注:这种方式需要确保代码中存在using namespace std::literals::string_literals;或者using namespace std;(后者会引入所有std命名空间的字面量),同时GDB版本支持C++11特性。

原因说明

test2的参数是const char*,字符串字面量"test"的类型正好匹配,所以可以直接调用;而test的参数是std::string,GDB无法自动完成隐式类型转换,必须显式构造std::string实例来匹配函数的参数类型,否则GDB无法找到对应的函数重载,从而报错。

内容的提问来源于stack exchange,提问作者Helen9999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:00:58