lundi 20 août 2018

error while distractor called

I have a class that has two field one of them is a pointer and another is int value to hold length of string sets in constructor.

class MyString 
{
    char* m_pchString;
    int m_nLength;
public:
    MyString(const char* pchString="")
    {

        m_nLength = strlen(pchString) + 1;
        m_pchString = new char(m_nLength);
        strcpy_s(m_pchString,m_nLength, pchString);
    }

    MyString(const MyString &Source)
    {
        m_nLength = Source.m_nLength;
        if (Source.m_pchString)
        {
            m_pchString = new char(m_nLength);
            strcpy_s(m_pchString,m_nLength,Source.m_pchString); 
        }
        else
        {
            m_pchString = 0;
        }
    }

    ~MyString() 
    {
        delete[] m_pchString;
        m_pchString = 0;
    }

    char* GetString()
    {
        return m_pchString;
    }

    int GetLength()
    {
        return m_nLength;
    }
};

Then use it in console application and create an object cHello .afterward create another object an assign it by cHello within a block

int main()
{
    MyString cHello ("Hello,World");
    {
        MyString cCopy = cHello;
    }

    std::cout << cHello.GetString();

    getchar();
    return 0;
}

when lifetime of cCopy over the distractor of cCopy called an error throw.What is the problem in these code?

Aucun commentaire:

Enregistrer un commentaire