Pergunta

class Foo{
    private: 
       int i;
    public:
       Foo(int a)
       {
          i = a;
       }

        int getI() {return i;}
};

int main()
{
    Foo* f;
    if(true)
    {
        Foo g(1);
        f = &g;
    }

    cout << f->getI() << endl;
    return 0;
 }

In the code above, the g object of Foo class will go out of scope once it exit the if clause. So when the cout statement is executed, will it be printing 1?

Foi útil?

Solução 3

The object will be destroyed, calling the object's destructor.

The pointer will still point to the same memory location.

Accessing it is an undefined behavior, so it could do anything at all.


You cannot assume the behavior of this, but if your code contains only this code then there might be a good chance that it will effectively print 1 as the memory will not have been overwriten.

But do not assume this will be the case !

Outras dicas

The behavior is undefined. It could do anything at all. You must absolutely avoid undefined behavior.

It will cause undefined behavior. Legally it can do anything: it could print 1, it could print 42, it could order a pizza or it could end all life in the universe. All are legal results. Undefined behavior is very bad.

Once g goes out of scope, it is no longer defined, f now points to an undefined object and dereferencing f, while not forbidden, is not supported in any defined way.

You get an Undefined behavior. You cannot know what cout will print...

Maybe sometimes it will print the correct value but you can be sure that the day of the demo it will not be correct...

It may. Or it may not. The object will be destroyed, the pointer will point to the same adress in memory.

But dereferencing this pointer is undefined behavior, and that's not what you want. Indeed, what's the use of a program which nobody can say what'll it do ?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top