sample1.cpp
#include <iostream>
int main()
{
int* aPtr = nullptr;
{
int a = 3;
aPtr = &a;
}
std::cout << *aPtr << std::endl;
return 0;
}
Output
3
I am able to access a
through aPtr
.
- Does that mean
a
is not deallocated even after it goes out of scope. - Does that mean
a
is deallocated only after the function in which it is defined unwinds. - Or is this an undefined behavior that currently outputs some value?
sampe2.cpp
#include <iostream>
struct Box
{
Box(int a_)
:a(a_)
{}
int getValue() const { return a;}
~Box()
{
std::cout << "Destructor called" << std::endl;
}
private:
int a;
};
int main()
{
Box* boxPtr = nullptr;
{
Box box = 23;
boxPtr = &box;
}
std::cout << boxPtr->getValue() << std::endl;
return 0;
}
Output
Destructor called
23
I am able to access box
through boxPtr
even after destructor of box
is called.
Aucun commentaire:
Enregistrer un commentaire