gpt4 book ai didi

c++ - 返回指向局部函数变量的指针

转载 作者:太空狗 更新时间:2023-10-29 20:46:13 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable's memory be accessed outside its scope?

我知道我不应该返回指向局部函数变量(局部堆栈变量)的指针,因为当函数返回时,变量将无效并且堆栈将被清理,除非我将这些变量设为静态或将它们分配到堆上。

下面的代码演示了:

const char* v1() {
return "ABC";
}

const char* v2() {
string s = "DEF";
return s.c_str();
}

const char* v3() {
static string s = "JHI";
return s.c_str();
}

cout << v1() << endl; // Output: ABC
cout << v2() << endl; // Output: garbage (♀ ╠╠╠╠╠╠╠╠)
cout << v3() << endl; // Output: JHI

但是,我返回了指向原始局部函数变量的指针,并且我能够获取它的值,尽管它不是静态的,如以下代码所示:

int i1() {
int i = 5;
return i;
}

int* i2() {
int i = 6;
return &i;
}

int* i3() {
static int i = 7;
return &i;
}

cout << i1() << endl; // Output: 5
cout << *i2() << endl; // Output: 6 !!
cout << *i3() << endl; // Output: 7

编译器只警告我返回局部变量或临时变量的地址 (Visual C++ 2008)。这种行为是否对所有编译器都很常见?编译器如何允许我使用指向局部函数变量的指针来访问它指向的值,尽管函数返回时该变量已失效?

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