在C ++中返回对静态局部变量的引用 [英] Returning reference to static local variable in C++

查看:344
本文介绍了在C ++中返回对静态局部变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题只是为了更好地理解C ++中的静态变量。

This question is just for my better understanding of static variables in C++.

我想我可以返回一个C ++中的局部变量的引用,因为变量应该在函数返回后继续存在。为什么这不工作?

I thought I could return a reference to a local variable in C++ if it was declared static since the variable should live-on after the function returns. Why doesn't this work?

#include <stdio.h>
char* illegal()
{
  char * word = "hello" ;
  return word ;
}

char* alsoNotLegal()
{
  static char * word = "why am I not legal?" ;
  return word ;
}


int main()
{
  // I know this is illegal
  //char * ill = illegal();
  //ill[ 0 ] = '5' ;
  //puts( ill ) ;

  // but why is this? I thought the static variable should "live on" forever -
  char * leg = alsoNotLegal() ;
  leg[ 0 ] = '5' ;
  puts( leg ) ;
}


推荐答案

非法。首先,在这两种情况下,返回一个指针的副本,指向具有静态存储持续时间的对象:字符串文字将在整个程序持续时间内生效。

The two functions are not itself illegal. First, you in both case return a copy of a pointer, which points to an object having static storage duration: The string literal will live, during the whole program duration.

但是你的 main 函数是关于未定义的行为。你不能写入字符串文字的内存:)你的主要功能可以削减到相同的行为

But your main function is all about undefined behavior. You are not allowed to write into a string literal's memory :) What your main function does can be cut down to equivalent behavior

"hello"[0] = '5';
"why am I not legal?"[0] = '5';

两者都是未定义的行为,在某些平台上崩溃(好!

Both are undefined behavior and on some platforms crash (good!).

编辑:注意字符串文字在C ++中有一个const类型(C中不是这样): N] 。您分配给非常量字符的指针会触发已弃用的转换(无论如何,良好的实现将会警告)。因为上面对const数组的写操作不会触发该转换,代码将会编译错误。真的,你的代码是这样做的。

Edit: Note that string literals have a const type in C++ (not so in C): char const[N]. Your assignment to a pointer to a non-const character triggers a deprecated conversion (which a good implementation will warn about, anyway). Because the above writings to that const array won't trigger that conversion, the code will mis-compile. Really, your code is doing this

((char*)"hello")[0] = '5';
((char*)"why am I not legal?")[0] = '5';

阅读 C ++字符串:[] vs *

这篇关于在C ++中返回对静态局部变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆