I've a question when it comes to pointers and allocation.
Lets say we've a class called MyVector.
class MyVector
{
private :
float *arr;
public :
MyVector()
{
arr = new float[20];
}
float* getVector()
{
return arr;
}
};
The question:
When i return it from my vector class, do i have to delete it both in the class and in main? Or, if i delete it in main, i deleted the same pointer?
Whats the difference between:
float* getVector()
{
return arr;
}
and
float*& getVector()
{
return arr;
}
pointers are not automatically call by-reference right?
Thanx for answers. Pointers sometimes screw with my brain.
class HoldInt
{
int *p;
public:
HoldInt() : p(newint()) {}
HoldInt(const HoldInt &from) : p(newint(*from.p)) {}
HoldInt(int i) : p(newint(i)) {}
HoldInt &operator=(const HoldInt &from)
{
*p = *from.p;
return*this;
}
void Value(int i)
{
*p = i;
}
int Value() const
{
return *p;
}
~HoldInt() //This is the destructor, same as default constructor but with tilde ~
{
delete p; //this is not done for you because you allocated the memory with new
}
};
This way you never have to worry about manually deleting the class' internal stuff - it's all handled for you at this point.
Thanx for the reply, but im not noob in c++. I'm just confused.
The question is: if a return a pointer from a class and store it in a variable in main, do i have to delete the pointer in main and in the class to prevent memory leak? Or, if i delete the pointer in main, do i destroy the pointer data in the class?
If you return a pointer from your class, you should not delete it outside of your class, the destructor does that. However, it may be safer if you use smart pointer in such cases, instead of your class.
But if you have a class that just return a new create pointer without assigning it to any internal members, than you have to delete that pointer out side of your class.
int main()
{
Something s;
//...
Thing *t = s.getStatus();
if(t)
{
//...
}
delete t; //it is your responsibility to delete it
//because how could the class possibly know when you were done with it?
//...
}