c++ - 为什么在复制赋值之前调用复制构造函数?

标签 c++ copy-constructor copy-assignment

class LinkedList
{
public:
    LinkedList() : _head(nullptr) {}
    LinkedList(ListElement *newElement) : _head(newElement) {}
    ~LinkedList() {  };
    LinkedList(const LinkedList& LL);
    LinkedList& operator=(LinkedList byValLinkedList);
private:
    ListElement *_head;
}
LinkedList::LinkedList(const LinkedList & LL)
{
    ListElement *curr = LL._head;

    // If Linked List is empty
    if (isEmpty() && curr != nullptr) {
        _head = new ListElement(curr->getValue());
        curr = curr->getNext();
    }

    ListElement *newNode = nullptr;
    while (curr) {
        newNode = new ListElement(curr->getValue());
        curr = curr->getNext();
    }
}

LinkedList& LinkedList::operator=(LinkedList byValLinkedList)
{

std::swap(_head, byValLinkedList._head);
return *this;
}


int main() {
    using namespace std;
    LinkedList LL1(new ListElement(7));
    //..... some insertions
    LinkedList LL2(new ListElement(5));
    //..... some insertions
    LL1 = LL2;  // What is the order ?
    // ..... do something else
    return 0;
}

When LL1 = LL2 is executed, which one is supposed to be called.

I expect the copy-assignment to happen. But the code was executed in the following order

  1. Copy Constructor
  2. Copy-Assignemnt
  3. Destructor

What am i doing wrong ? and why was the destructor called?

最佳答案

 LinkedList& operator=(LinkedList byValLinkedList);

您的复制分配按值获取其参数。这意味着

 LL1=LL2;

需要制作 LL2 的拷贝,以便按值传递它。这就是“按值(value)传递”的意思。因此,复制构造函数。

为避免进行复制构造,赋值运算符必须通过引用获取其参数,而不是:

 LinkedList& operator=(const LinkedList &byValLinkedList);

这意味着,当然,您不能完全使用 std::swap 实现赋值运算符。但那将是一个不同的问题......

简而言之,您有两个选择:实现两个复制构造函数,一个接受 const 引用,一个不接受,后者能够使用 std::swap。或者,将 _head 声明为 mutable

关于c++ - 为什么在复制赋值之前调用复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535370/

相关文章:

c++ - 标准::查找 'error no matching function'

不同包中的java复制构造函数

c++ - 多个 emplace_back 额外调用复制构造函数

c++ - 这个复制赋值操作安全吗?

数组与标量中的python赋值

c++ - 在 C++ 中,具有 const 数据成员的类可以没有复制赋值运算符吗?

c++ - 无法在初始化中将 'Date' 转换为 'int' 错误

c++ - 在C++中识别多余头文件的工具

c++ - 在主体中调用方法与在构造函数列表中调用方法之间的区别

c++ - 通过 out 参数处理错误会导致内存泄漏吗?