从复制构造函数调用构造函数 [英] Calling constructor from copy constructor

查看:93
本文介绍了从复制构造函数调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++ 11中,我们可以从另一个构造函数调用一个构造函数。因此,除了定义副本构造函数外,我们还可以每次调用该构造函数吗?就像这段代码一样:

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?

是的,您可以

其中之一委派构造函数的优点是,通过在某些可能需要全套参数的构造函数中进行通用初始化来避免代码重复。

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.

这篇关于从复制构造函数调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆