我有以下代码.
#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++的这一段中,delete this讨论了构造的使用.列出了4个限制.
限制1到3看起来很合理.但是为什么限制4在那里我"必须不检查它,将它与另一个指针进行比较,将它与NULL进行比较,打印它,投射它,用它做任何事情"?
我的意思this是又一个指针.为什么我不能把reinterpret_cast它int或者叫它printf()输出它的值?
我有一个使用引用计数机制的类.delete this当引用计数降为零时,最终通过调用来销毁此类的对象.我的问题是:我之后可以使用本地堆栈变量delete this吗?这是一个更具体的例子:
class RefCountedClass
{
public:
RefCountedClass(Mutex& m) :
mutex_(m)
{}
.
.
.
private:
Mutex& mutex_;
void RemoveReference()
{
// As I understand, mutex_ will be destroyed after delete,
// but using m is all right because it is on-stack and
// references an external object. Am I right?
Mutex& m = mutex_;
m.Acquire();
--recount_;
if (refcount <= 0) delete this;
m.Release();
}
};
Run Code Online (Sandbox Code Playgroud)