Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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:

  • Use size_t instead of int to store sizes
  • Use constructor initilization list instead of assignment inside constructor body
  • Know the difference between new char [len] vs new char(); former allocates an array while the latter a char initialized to 0
  • Know that when you manage objects in free store, you've to implement an assignment operator, destructor, etc. a.k.a The Rule of Three/Five.
  • Allocating memory for a pointer and then losing its reference by allocating something else without releasing it will leak memory
  • Using std::string will be better since it's tried and tested
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top