【发布时间】:2019-09-23 07:14:33
【问题描述】:
(我正在使用库libmicrohttpd)
像这样的 const char * 可以正常工作:
const char *page = "Hello World";
MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_PERSISTENT);
但是给 const char * 赋值一个字符串会在客户端输出一个奇怪的字符串:
std::string str = "Hello World";
const char *page = str.c_str();
MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_PERSISTENT);
或:
std::string str = "Hello World";
MHD_create_response_from_buffer(strlen(page.c_str()), &page[0], MHD_RESPMEM_PERSISTENT);
客户端上第二个和第三个代码 sn-ps 的输出是“ججججججججججج”。不是“Hello World”。
为什么?
【问题讨论】:
-
我猜字符串的生命周期在你使用它之前就结束了,如果你使用
MHD_RESPMEM_MUST_COPY而不是MHD_RESPMEM_PERSISTENT,这将正常工作。 -
@Hasturkun 哇,没想到,谢谢!
-
我认为提及您使用的库可能会有所帮助,并澄清您描述的观察结果是否在调用函数时立即发生,或者这些是否是在输出之前完成的其他操作观察到。
标签: c++ string parameter-passing