<< PreviousNext >>

Answer to Broken container

The problem is that we are actually not keeping the value we inserted into the container when we are calling contain(&v1). Think of it this way:

int v1 = 10;
{
  int *ptrV1 = &v1;
  contain(ptrV1);
}

The problem is that since contain takes a reference to ptrV1 in this case, we need to keep ptrV1 alive. This will not happen when we are using the shorthand contain(&v1). Since ptrV1 is temporary, it is undefined what happens when we try to access the previous location of ptrV1, when it has gone out of scope. Since that is undefined, the compiler is free to reuse the space of ptrV1 to other things, which is why we see strange results in the output. In the case of Visual Studio, it seems like it allocates space for all temporary variables separatly when not having optimizations turned on, which is why I did not notice the problem earlier.

Problem

Comments

New comment

You can use GitHub flavored markdown here. Parsed by Parsedown, which does not support all of GitHub's features. For example, specifying the language of code listings is not supported.

Name: