Why might the following hang the program?
Now that I've got SmartPointers, I decided to try DumbPointers, which do the terribly difficult job of calling "delete" in a destructor. Deciding to continue my tests of storing arrays in SmartPointer, using a DumbPointer, I recalled a previous error and tried this:
DumbP开发者_高级运维ointer<char> dumbPointer = "Hello World\0";
For undefined reasons of "Perhaps that's not a pointer or proper pointer?", it causes the program to hang. Naturally, I'd like to know why, with an eye toward solving said problem. I will now provide the terribly complex DumbPointer code (maybe I should go to sleep) below: (Let me re-assure you: The destructor is called)
#pragma once
#include "stdafx.h"
template <typename T> class DumbPointer
{
private:
T* myPtr;
public:
T* Value() { return myPtr; }
DumbPointer(const DumbPointer<T>& a)
{ throw new "No assignments between DumbPointer."; }
DumbPointer(T* ptr) { myPtr = ptr; }
DumbPointer(T value) { myPtr = &value; }
~DumbPointer() { delete myPtr; }
operator T*() { return myPtr; }
T* operator ->() { return myPtr; }
};
You must only delete
pointers that you allocated with new
. You pass a string constant to your DumbPointer, which has static allocation.
In addition to Frederik's comment, I would just add that there's absolutely no reason to assign a string constant to a smart pointer.
Since there's absolutely nothing to delete here, just assign it to a plain old char*
pointer. Again, there's nothing that needs deleting or cleaning up.
精彩评论