Custom Assignment Operator with raw pointer member
Nov 2, 2013 at 6:19pm UTC
Hi, I have a question to do with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#include <iostream>
//#include <memory>
class MyData
{
public :
MyData(int num = 0) : myWord("TEST" ),number(3)
{
parentdata = new float (num);
}
MyData(const MyData& other) : myWord("TESTING" ),number(other.number),
parentdata(new float (*other.parentdata))
{
int test = 0;
}
void Remove()
{
delete parentdata;
}
inline void setWord(const std::string word)
{
myWord = word.c_str();
}
friend std::ostream& operator <<(std::ostream& os,const MyData& data)
{
os<<"DATA" <<(*data.parentdata);
return os;
}
/*MyData& operator=(const MyData& rhs)
{
if(&rhs != this)
{
delete parentdata;
parentdata = 0;
myWord = rhs.myWord;
number = rhs.number;
parentdata = new float(*rhs.parentdata);
}
return *this;
}*/
void setValue(int val)
{
*parentdata = val;
}
private :
float *parentdata;
int number;
const char * myWord;
};
int main()
{
MyData da_data(1);
MyData da_data2 = da_data;//(da_data);
da_data2.setValue(4);
MyData data[2];
data[0] = da_data;
data[1] = da_data2;
//da_data.Remove();
da_data2.Remove();
std::cout<<data[0]<<std::endl;
std::cout<<data[1]<<std::endl;
int test = 0;
std::cin>>test;
return 0;
}
If you run this, it should print out:
DATA 1
DATA somerandomnumberbecauseofdeletedpointer
My question is, if you uncomment my overloaded assignment operator, the print out becomes:
DATA1
DATA4
Why does it do this? What am I doing wrong?
Nov 2, 2013 at 6:28pm UTC
I'm guessing it has to do with the assignment of: data[0] = da_data; etc.
EDIT: Yes ok, I figured it out. When I assigned the 2 datas into the array I basically made a deep copy of them so they were 2 new objects.
If my assignment operator was like this, it would be the effect I desired.
1 2 3 4 5 6 7 8 9 10 11 12 13
MyData& operator =(const MyData& rhs)
{
if (&rhs != this )
{
myWord = rhs.myWord;
number = rhs.number;
parentdata =(rhs.parentdata);
}
return *this ;
}
Thanks :P
EDIT2: Hmm, possibly this doesn't make sense..how come when I "Remove()" da_data2 when using this assignment code it doesn't null out da_data pointer? They pointed to the same place, so doesn't deleting a pointer then free the memory at the same address for both?
Last edited on Nov 2, 2013 at 6:43pm UTC
Topic archived. No new replies allowed.