jeudi 30 août 2018

Is the stack variable deallocated when it goes out of scope?

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.

  1. Does that mean a is not deallocated even after it goes out of scope.
  2. Does that mean a is deallocated only after the function in which it is defined unwinds.
  3. 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