I want to write my simple smart-pointer but I got a problem. This is only part of the code but I spotted the problem here:
#include <iostream>
using namespace std;
class Number{
public:
Number(){}
Number(float value):_value(value){cout << "Creating Object\n";}
~Number(){cout << "Destroying Object\n";}
private:
float _value;
};
class Smart_ptr {
public:
Smart_ptr(){}
Smart_ptr(Number* other):Ptr(other){}
Smart_ptr(const Smart_ptr &other):Ptr(other.Ptr){} // PROBLEM !!!
Smart_ptr& operator=(Smart_ptr& other){
if(this!=&other)
{
if(Ptr!=NULL)delete Ptr; // is that properly writen ?
Ptr=other.Ptr;
other.Ptr=NULL;
}
return *this;
}
~Smart_ptr(){if(Ptr!=NULL) delete Ptr;}
private:
Number* Ptr;
};
int main(){
Smart_ptr number5 = new Number (5); // <--- Creating Object
{
Smart_ptr number6 = number5;
} // <--- Destroying Object
std::cout<<"END"<<std::endl;
}
I should get output like this:
Creating Object
Destroying Object
END
but instead I got double free or corruption (fasttop) and memory map error.
I know that the problem is double deleting number5
(it should be deleted in the braces in main()
) but I don't know how to deal with it.
shared_ptr<T>
like smart pointer. You need to count how many references there are and check in your destructor before callingdelete
. You only want to calldelete
when there is one reference. – bku_dryttnumber6
you are invoking the copy constructor, not the assignment operator. – quamrana