0

I've implemented a Smart Pointer class, when i tried to compile, it stops on a specific line and i get this messege: Unhandled exception at 0x00418c38 in test.exe: 0xC0000005: Access violation reading location 0xfffffffc.

my code is:

  template <class T>
class SmartPointer
{
    private:
        T* ptr;
        int* mone;
    public: 
        SmartPointer() : ptr(0), mone(0) //default constructor
        {
            int* mone = new int (1); 
        }

         SmartPointer(T* ptr2) : ptr(ptr2), mone(0)
         {
             int* mone = new int (1);        
         }

        SmartPointer<T>& operator= (const SmartPointer& second) //assignment operator
        {
            if (this!= &second)
            {
                if (*mone==1)
                {
                    delete ptr; 
                    delete mone;
                }

                ptr = second.ptr;
                mone = second.mone;
                *mone++;
            }
            return *this;
        }

        ~SmartPointer() // Destructor
        {
            *mone--;
            if (*mone==0)
            {
                delete ptr;
                delete mone;
            }
        }
};

i also have a * and & overloading functions and a copy constructor.

it stops here:

if (*mone==0)

could you please help me?? thaks

user3671163
  • 1
  • 1
  • 1
  • Please compile with all warnings & debug info (with [GCC](http://gcc.gnu.org/) that means `g++ -Wall -g`). Then use your debugger (`gdb` on Linux systems). Also, use the STL smart pointers. – Basile Starynkevitch May 24 '14 at 07:19

1 Answers1

5
SmartPointer() : ptr(0), mone(0) //default constructor
{
  int* mone = new int (1);  // PROBLEM
}

You're declaring a local variable called mone inside the constructor. This hides your member variable with the same name. So your member variable is initialized with 0 (from the initializer list), but never set to point to anything.

Use this instead:

  mone = new int (1);

Or do that directly:

SmartPointer() : ptr(0), mone(new int(1)) {}

The statements *mone++; and *mone--; in there won't do what you they they do. The postfix increment/decrements are applied to the pointer, not the thing it points to. i.e. they are parsed as:

*(mone++);

You need parens:

(*mone)++;

Make sure you've got your compiler warnings turned on to the max, both clang and g++ signal that there's something fishy with those lines.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 1
    +1 once this is fixed, the OP may want to do something about the `*mone++` and `*mone--`, which I guarantee doesn't do what they think it does. That crash is impending. – WhozCraig May 24 '14 at 07:24