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
- Copy Constructor
- Copy-Assignemnt
- 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/