Reputation: 196
I have doubt regarding copy constructor for a char*
data member.
I have my code as,
#include<iostream>
using namespace std;
class Test
{
char *str;
int length;
public:
Test(){}
Test(char *a)
{
length = strlen(a)+1;
str = new char(length);
str = strncpy(str,a,length);
}
Test(const Test &t)
{
length = t.length;
if(t.str)
{
str = new char(length);
str = strncpy(str,t.str,length);
}
else
str = 0;
}
void out(){cout<<str;}
};
int main()
{
Test t("Test");
Test t1 = t;
t1.out();
return 0;
}
In case of constructor and copy constructor instead of using strncpy
to copy the data member value, if I use:
Test(char *a)
{
str = new char();
str = a;
}
Test(const Test &t)
{
if(t.str)
{
str = new char();
str = t.str;
}
else
str = 0;
}
Will this also work? If yes, which method is preferable?
Upvotes: 2
Views: 9758
Reputation: 5124
Not only the second version won't work, it will also provide you with a memory leak.
You first allocate memory to str
, then you put in str the pointer pointing at the other object's string which means:
1. You no longer can access the memory you allocated.
2. Once you delete the string in one of the objects, it will be deleted in the other one too.
(*) you should also add an assignment operator.
Upvotes: 1
Reputation: 32884
In case of constructor and copy constructor instead of using strncpy to copy the data member value, if I use [code doing pointer copy]
I see that instead of strncpy
you directly assign the pointer to the passed in string pointer. Will this work? No, what you're doing is just a pointer copy and not what the data the pointer is pointing to i.e. you need to deep copy and not shallow copy. You can use strncpy
or std::copy_n
.
Multiple other issues:
size_t
instead of int
to store sizesnew char [len]
vs new char()
; former allocates an array while the latter a char
initialized to 0std::string
will be better since it's tried and testedUpvotes: 0