相关疑难解决方法(0)

可以在其范围之外访问局部变量的内存吗?

我有以下代码.

#include <iostream>

int * foo()
{
    int a = 5;
    return &a;
}

int main()
{
    int* p = foo();
    std::cout << *p;
    *p = 8;
    std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)

而代码只是运行而没有运行时异常!

输出是 58

怎么会这样?本地变量的内存不能在其功能之外无法访问吗?

c++ memory-management local-variables dangling-pointer

990
推荐指数
19
解决办法
26万
查看次数

为什么从函数返回向量是可以的?

请考虑此代码.我已经多次看过这种类型的代码了.words是一个本地向量.如何从函数中返回它?我们可以保证它不会死吗?

 std::vector<std::string> read_file(const std::string& path)
 {
    std::ifstream file("E:\\names.txt");

    if (!file.is_open())
    {
        std::cerr << "Unable to open file" << "\n";
        std::exit(-1);
    }

    std::vector<string> words;//this vector will be returned
    std::string token;

    while (std::getline(file, token, ','))
    {
        words.push_back(token);
    }

    return words;
}
Run Code Online (Sandbox Code Playgroud)

c++ scope stl vector standard-library

106
推荐指数
4
解决办法
13万
查看次数