c++ - 多参数复制构造函数

标签 c++ copy-constructor

我正在学习 C++,并且正在阅读 C++:The Complete Reference 中的复制构造函数。书上说的

It is permissible for a copy constructor to have additional parameters as long as they have default arguments defined for them. However, in all cases the first parameter must be a reference to the object doing the initializing.

但我很困惑,我们将如何传递这些附加参数?我确信应该有一些方法没有在书中给出而且我无法弄清楚。谁能帮帮我?

编辑: 也可以在所有三种情况下传递这些额外参数,即

  • 当一个对象显式初始化另一个对象时,例如在声明中
  • 当一个对象的拷贝被传递给一个函数时
  • 生成临时对象时(最常见的是作为返回值)

最佳答案

这是一个简单的例子:

class A {
    //...
public:
    A (const A&, bool deep = false) {
        if (!deep) { /* make a shallow copy */ }
        else { /* make a deep copy */ }
    }
};

void foo (A x) { /*...*/ }
A bar () { /*...*/ return A(); }
A a_var;

在此示例中,参数默认为 false,这意味着默认的复制构造函数将很浅。

A b(a_var);       // b gets a shallow copy of a
foo(b);           // foo() receives a shallow copy

但是,可以通过在第二个参数中传递 true 来实现深拷贝。

A b(a_var, true); // b gets a deep copy of a
foo(A(b, true));  // foo receives a shallow copy of a deep copy

类似地,对于返回 A 的函数,返回的拷贝会很浅,因为它使用默认值,但接收方在接收到它时可以使其变深。

A b(bar());       // shallow
A b(bar(), true); // deep

请记住,当您定义一个复制构造函数时,很可能意味着您将需要定义一个析构函数并重载赋值运算符(三规则)。

关于c++ - 多参数复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10943491/

相关文章:

c++ - 使用模板使不同长度的项目保持在堆栈中?

java - 多态性的 C++ 模板? "Use of class template requires template arguments"

c++ - 复制构造函数 Big 3 C++ 问题

C++ 按值返回

c++ - 带有模板参数的函数指针

c++ - 直接从输入缓冲区以相反顺序读取数组

c++ - 是否有一种非重复的方式允许程序员在成员初始化的复制和 move 语义之间进行选择?

c++ - 我不明白 clang 和 GCC 相对于 C++14 中的 [class.copy]/9 获得的结果。

c++ - clang 与 gcc 运行时差异 : c++ class template built w clang crashes w/o copy constructor, 使用复制构造函数构建 gcc 崩溃

c++ - Kinect SDK 1.8 实例 Winbase.h 报错