Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当字符串超出范围时,将string::c_str()赋值给const char* 我对C++的基本用法有怀疑。下面的代码是用gcc/LInux编译的,可以正确打印出来_C++_String_Char_Constants - Fatal编程技术网

当字符串超出范围时,将string::c_str()赋值给const char* 我对C++的基本用法有怀疑。下面的代码是用gcc/LInux编译的,可以正确打印出来

当字符串超出范围时,将string::c_str()赋值给const char* 我对C++的基本用法有怀疑。下面的代码是用gcc/LInux编译的,可以正确打印出来,c++,string,char,constants,C++,String,Char,Constants,字符串test超出范围,因此其c_str()值应该无效,不是吗?是我错了还是我误解了const char*的意思 #include <iostream> int main(){ const char* a = "aaaa"; std::cout << a; { std::string test("bbbb");a=test.c_str();} std::cout << a; a =

字符串
test
超出范围,因此其
c_str()
值应该无效,不是吗?是我错了还是我误解了
const char*
的意思

   #include <iostream>
   int main(){
     const char* a = "aaaa";
       std::cout << a;
       { std::string test("bbbb");a=test.c_str();}
       std::cout << a;
       a = "cccc";
       std::cout << a;
   }


   aaaabbbbcccc
   // print out without any problem
#包括
int main(){
常量字符*a=“aaaa”;

std::cout你是对的,你的代码是无效的,因为它使用了一个生命周期已经结束的对象。它是“偶然”工作的,你不能依赖它。

因为
test
超出了范围,你所做的是未定义的行为。不要对它如何工作做出假设


它也可能是segfault,行为仍然是正确的。UB是UB。

string
对象超出范围时,
a
指向的内存仍将存在。我认为标准没有提到在字符串被破坏时清除实际内存位置的任何内容。

这可能是因为字符串池。无论如何,它是未定义的行为。一旦字符串超出范围,我们就不应该使用c_str()输出。

程序调用未定义的行为。当程序这样做时,编译器可以自由地执行它希望执行的任何操作,包括创建一个可以按预期工作的程序

它以这种方式工作的可能原因如下。在内部块的末尾,
test
超出范围并运行其析构函数。这将释放用于保存实际字符串的内存块以供其他使用,但内存未被清除(这将是浪费时间)。由于某种原因,在打印出
bbbb
之前,不会重新使用由此释放的内存


(请注意,
cccc
赋值和打印输出是有效的。)

您是否暗示OP在访问
malloc()
ed指针
free()之后,正在(不适当地)使用延迟初始化
ed?@moshbear类似的东西是的。嗨,a.J.这是UB的意思吗?这是未定义行为最糟糕的症状,目前正在做你认为应该做的事情