【问题标题】:Same address, but different content地址相同,内容不同
【发布时间】:2015-12-24 01:52:14
【问题描述】:

我正在使用字符串流来获取文本文件的内容(实际上,它是一个着色器代码源),以便将其传递给采用 const char* const* (glShaderSource) 的函数。起初,我是这样做的

std::stringstream buffer;
buffer << input.rdbuf();

char const *code = buffer.str().c_str();
glShaderSource(id, 1, &code, 0);

它不起作用,因为 code 的内容不是预期的。实际上,如果我这样做:

std::stringstream buffer;
buffer << input.rdbuf();

char const *code = buffer.str().c_str();

printf("Code*: %p\n", code);
printf("Buff*: %p\n", buffer.str().c_str());

printf("Code0: %c\n", code[0]); // ERROR: prints garbage.
printf("Buff0: %c\n", buffer.str().c_str()[0]);

printf("Code1*: %p\n", &code[1]); // ERROR: prints garbage.
printf("Buff1*: %p\n", &buffer.str().c_str()[1]);

printf("Code1: %c\n", code[1]);
printf("Buff1: %c\n", buffer.str().c_str()[1]);

我得到相同的指针值输出,缓冲区中字符的正确输出,但 code 内容的随机输出。

现在,如果我使用这样的功能:

void workaround(char const *code) {
    printf("Code*: %p\n", code);
    printf("Code: %s\n", code);
}

-------------------------------------

std::stringstream buffer;
buffer << input.rdbuf();

workaround(buffer.str().c_str());

printf("Buff*: %p\n", buffer.str().c_str());
printf("Buff: %s\n", buffer.str().c_str());

我得到了指针和字符串内容的正确值。

为什么这段代码有效,而不是第一个?

【问题讨论】:

  • 你能详细说明有趣/意外吗?
  • 无法复制:ideone.com/9G45jT
  • 不要将解决方案放在问题中,将其作为答案发布。
  • 有一个dreamlax发布的正确答案,但由于某种原因被删除了..

标签: c++ string pointers constants


【解决方案1】:

我发现了问题:std::stringstream 返回的字符串是临时的,只在表达式结束前有效。

为了延长 buffer.str() 的有效期,可以在对象上创建一个引用。该值的预期寿命将延长至参考值之一。

以下代码有效:

std::string const &string = buffer.str();
char const *code = string.c_str();
glShaderSource(id, 1, &code, 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多