相关疑难解决方法(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万
查看次数

249
推荐指数
7
解决办法
7万
查看次数

std :: bind如何以及为什么保持指针活着

将方法与对象指针绑定并在之后删除该对象,该方法仍然是可调用的.

struct A {
    void b(){std::cout << "SUHDU" << std::endl;}
};

int main(int argc, const char * argv[])
{
    A *a = new A;
    auto f1 = std::bind(&A::b, a);
    auto f2 = std::bind(&A::b, std::ref(a));

    f1();
    f2();

    delete a;
    f1(); // still outputs SUHDU
    f2(); // still outputs SUHDU
}
Run Code Online (Sandbox Code Playgroud)

为什么std::bind这样做,它是如何做到的?

c++ c++11

2
推荐指数
1
解决办法
335
查看次数

是c_str()在堆中分配内存?

最近我有c_str()的问题.下面是示例代码片段

#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
class har{

    public:
    string h;
    har(string str){
        h=str;
    }
};

int main(){


har *hg=new har("harish");
const char *ptr=hg->h.c_str();
delete hg;
cout<<ptr<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到输出"harish"....我已经销毁了对象,但我仍然得到输出..是c_str()再次在堆中分配内存.

c++

0
推荐指数
1
解决办法
180
查看次数