c++中这个变量的作用域是什么?

what is the scope of this variable in c++?

如果我定义这样的函数

std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

如果我使用这个 temp,它通过引用传递给另一个函数,例如

void displaystring(std::string &temp)
{
    std::cout<<temp;
}

当我通过引用 displaystring 函数传递它时,string temp 是否仍然在范围内?

变量的范围是它被声明的范围。 std::string temp; 在函数体 returnstring 内声明,因此函数体是变量的范围。它是一个自动变量,因此它的生命周期在其范围结束时结束并自动销毁。

returned 引用将无效(即它是悬空引用)。如果您试图通过无效引用访问不存在的对象,那么程序的行为将是未定义的。

要修复此功能,一个简单的解决方案是 return 一个值。

没有。 temp 的范围仅限于声明它的块。因为你在堆栈上声明它(你没有使用关键字new),所以变量 temp 将在你退出函数的那一刻被销毁。 保留变量的唯一方法是将 temp 的值复制到函数外部的变量。例如,这会起作用:

std::string returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

因为 return 值是一个副本而不是一个引用,你可以这样做 std::string returned_string = return字符串(ist); 并将 temp 的值复制到一个新声明的变量中,该变量可用于您的 displaystring 函数。

一般来说,我会避免在函数内声明函数范围之外需要的变量。相反,只要您在函数内部 returning 变量,就按值 return(但是,不推荐用于大型数组和对象)。

不,因为 temp 变量是 returnstring 函数的局部变量,一旦代码脱离 retuernstring 函数,temp 变量就不再有效。 如果您想发送参考并获得答案,那么更好的选择是通过参考发送参数,如下所示,

void copyLineAsString(std::istringstream &ist, std::string& tempString)
{
    std::getline(ist,tempString);
    return;
}

对于良好的编码习惯,我对您的代码几乎没有其他建议, 切勿使用 '&' 作为 return 类型/return 引用变量。对函数名称使用驼峰式大小写或 _ 分隔符(例如 returnString 或 return_string)。

this 是引用变量,引用调用它的当前 class 对象。它的范围仅在 class 内,并且与调用它的对象的生命周期相同。