问题
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