Boost logo

Boost :

From: Moore, Dave (dmoore_at_[hidden])
Date: 2002-04-10 08:09:55


Markus Schöpflin writes:

Boosters,

the current implementation of shared_ptr allows the following
program to compile with MSVC6SP5.

#include <boost/shared_ptr.hpp>
boost::shared_ptr<int> p_i;
int main()
{
  p_i = 42;
  return 0;
}

The line p_i = 42; generates no assembly instructions at all, it
is simply ignored.

This is especially dangerous as the compiler belives this to be
the same as p_i = new int(0) which also doesn't generate any
assembly instructions.

-- End Original Message --

At first, I was going to dismiss this as "Oh, the compiler optimized it away
because it was never used. However, I expanded the test somewhat.
Shouldn't testa() and testb() be equivalent? I thought p_i = &i would
generate a temporary boost::share_ptr<int> via the explicit shared_ptr(T * p
= 0) constructor.

Even if I'm wrong about that, is this a compiler bug? It seems that either
code should be generated -or- an error/warning generated because it thinks
it can't convert int* to shared_ptr<int> ???

Thanks for the clarification.
Dave

Code follows:

#include <boost/shared_ptr.hpp>

boost::shared_ptr<int> p_i;
int i;

int testa()
{
        i = 5;
        p_i = &i; // This line generates no code whatsoever
                        // Yet compiles w/ no warnings
        *p_i = 0; // This crashes.
        return i;
}

int testb()
{
        i = 5;
        boost::shared_ptr<int> _temp(&i);
        p_i = _temp;
        *p_i = 0;
        return i;
}

int main()
{
        testa();
        testb();

        return i;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk