1
#include <iostream>
using namespace std;

class A
{
private:
   int m_i;
   friend int main(int argc, char const *argv[]);
public:
   A (int i = 0):m_i(i){};
   void display()
   {
       cout << m_i << endl;
   }
   int result() {return m_i;}
};

void createA(A *pa)
{
   pa = new A(1);
}

A* createA()
{
   A a(2);
   return &a;
}

void createAonstack()
{
   A a(3);
}

int main(int argc, char const *argv[])
{
   A a;
   A * pa = &a;
   pa->display();
   createA(pa);
   pa->display();

   A * a2 = createA();
   cout << a2->m_i << endl;
   createAonstack();
   cout << a2->m_i << endl;
   return 0;
}

The results of the program above is

0
0
2
3

How to explain the result 2 and 3? From my understanding, the object created in function createA() should be deconstructed, and the pointer it returns should point to NULL, but why a2->m_i can be 2. And the 3 is even more confusing, as it seems that the function createAonstack() has nothing to do with a2.

ryecao
  • 13
  • 3

3 Answers3

2

You said

From my understanding, the object created in function createA() should be deconstructed, and the pointer it returns should point to NULL, but why a2->m_i can be 2.

It is true that

the object created in function createA() should be deconstructed

It is not true that

and the pointer it returns should point to NULL

The pointer returned by createA is non-NULL even though it is an invalid pointer to use in the calling function.

but why a2->m_i can be 2.

It's pure coincidence. It really is undefined behavior. Anything can happen when you dereference a2.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • So can I put this in this way: the object is deconstructed, but the data the pointer pointing to has not been but open to rewritten? – ryecao Jun 20 '14 at 16:21
  • @ryecao, that's the behavior you are observing in your run time environment. A different environment, even using different compiler options in your environment, is likely to exhibit different behavior. – R Sahu Jun 20 '14 at 16:28
1

Function createA() returns a pointer on a local variable, that is destroyed at quitting the function, so anything can happen, direct crash, or worse, the program will work as if everything is ok.

As Bjarne Stroustrup said: C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.

kebs
  • 6,387
  • 4
  • 41
  • 70
0

As a quick tip, some more differentiable naming conventions might help readability in the future, as I personally find it a little hard to follow.

However, from what I can tell, it's a scoping problem. CreateA() produces a local pointer, and when it leaves that function's scope, it's lost. So whatever you're actually accessing is essentially random.

NeatoBandito
  • 110
  • 1
  • 10