简体   繁体   中英

Calling constructor from copy constructor

From c++ 11 we can call a constructor from another constructor. So instead of defining copy constructor can we call the constructor every time? Like in this piece of code :

class MyString
{
private:
    char *ptr;
    int m_length;
public:
    MyString(const char *parm = nullptr) : m_length(0), ptr(nullptr)
    {
        if (parm)
        {
            m_length = strlen(parm) + 1;
            ptr = new char[m_length];
            memcpy(ptr, parm, m_length);
        }
    }
    MyString(const MyString &parm) : MyString(parm.ptr)
    {

    }
};

Is there any ill effect to this approach? Is there any advantage of writing traditional copy constructor?

So instead of defining copy constructor can we call the constructor every time?

Yes, you can

One of the advantages of delegating constructors is avoiding code duplication by having common initialization in some constructors that might require a full set of arguments.

Is there any advantage of writing traditional copy constructor?

The capability to do construction delegation is not related to the need of defining the copy constructor or any other special constructors. You need to define them if necessary.

So instead of defining copy constructor can we call the constructor every time?

Yes, you can.

Is there any ill effect to this approach? Is there any advantage of writing traditional copy constructor?

Behavior-wise, there is no ill effect with your approach. With the member variables you have, IMO your approach is the most appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM