Calling constructor from copy constructor

孤街醉人 提交于 2019-12-20 06:16:22

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/53954356/calling-constructor-from-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!