考虑以下代码:
const char* someFun() {
// ... some stuff
return "Some text!!"
}
int main()
{
{ // Block: A
const char* retStr = someFun();
// use retStr
}
}
Run Code Online (Sandbox Code Playgroud)
在函数中someFun(),"Some text!!"存储的位置(我认为它可能在ROM的某个静态区域)以及它是什么范围 一生?
指向的内存是否会在retStr整个程序中被占用,或者在块A退出后被释放?
我读到我们不应该返回局部变量的指针或引用。因此,在下面给出的示例中,我知道当我编写:return i;inside function时foo,我返回对局部变量的引用。在函数外部使用该引用将导致未定义的行为。
#include <iostream>
const int& foo()
{
int i = 5;
return i;//returning reference to a local variable
}
const int& func()
{
return 5;
}
int main()
{
const int& ref = func();
const int& f = foo();
std::cout<<f<<std::endl; //I know this is undefined behavior because we're using a reference that points to a local variable
std::cout<<ref; //But IS THIS UNDEFINED BEHAVIOR too?
}
Run Code Online (Sandbox Code Playgroud)
return 5;我的问题是,对于function 内部的return 语句是否同样适用func。我知道在 C++17 中存在强制复制 …
编辑:关于为什么此问题中的代码有效的问题已通过重复标记中的链接问题得到解答.关于字符串文字生命周期的问题在这个问题的答案中得到了回答.
我试图了解如何以及何时const char *取消分配指向的字符串.
考虑:
const char **p = nullptr;
{
const char *t = "test";
p = &t;
}
cout << *p;
Run Code Online (Sandbox Code Playgroud)
离开内部范围后,我希望p是一个悬垂的指针const char *.但是在我的测试中并非如此.这意味着t即使在t超出范围之后,实际值仍然有效且可访问.
这可能是由于通过将它绑定到const引用来延长临时的生命周期.但我不做这样的事情,甚至通过t在成员变量中保存引用并从以后打印不同函数的值仍然给我正确的值.
class CStringTest
{
public:
void test1()
{
const char *t = "test";
m_P = &t;
test2();
}
void test2()
{
cout << *m_P;
}
private:
const char **m_P = nullptr;
};
Run Code Online (Sandbox Code Playgroud)
那么t这里价值的生命周期是多少?我会说我通过取消引用指向超出范围的变量值的指针来调用未定义的行为.但它每次都有效,所以我认为情况并非如此.
尝试其他类型的时候QString:
QString *p = …Run Code Online (Sandbox Code Playgroud)