gpt4 book ai didi

C++ 字符串.c_str()

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:20 24 4
gpt4 key购买 nike

如果使用 g++clang++,我得到 ++my string==my string##my string--。而MSVC和Intel Compiler,则是++==my string##my string--

为什么?

#include <string>
#include <iostream>

using namespace std;

string test()
{
string s0 = "my string";
return s0;
}

int main()
{
string s = test();
const char* s1 = test().c_str();
const char* s2 = s.c_str();
cout << "++" << s1 << "==" << s2 << "##" << test().c_str() << "--" << endl;
return 0;
}

这是未定义的行为吗?

最佳答案

在评论中,你问:

Why test().c_str() can work but s1 not?

test().c_str() 仅适用于某些上下文,并非所有上下文。

std::cout << test().c_str() << std::endl;

保证工作,因为 test() 返回的临时值需要在语句执行完成之前保持事件状态。

另一方面,

char const* s1 = test().c_str();
std:cout << s1 << std::endl;

是未定义的行为,因为临时对象不需要在第一行执行完成后继续存在。

关于C++ 字符串.c_str(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com