0
Follow
0
View

Does the copy constructor need to free resources? Can a shallow copy of the resource on the right of a be implemented in a=a+b?

dsunzhaogong 注册会员
2023-02-27 23:12

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > for problem, if the copy assignment function to release of the original resources, so when the function returns, the original resources has been released, This causes a to become a dangling pointer. Therefore, there is no need to release the original resource in the copy assignment function. If you need to free resources, you can do so in a destructor.

For problem two, if you want to avoid deep copying of the a on the right, consider implementing the move semantics to avoid creating new objects when you overload the + operator. When implementing move semantics, you can use an rvalue reference to accept the argument to the right, while using std::move() in the function to cast the argument to an rvalue, thereby moving the resource. For example:

String operator+(String&& rhs) {
  // 进行资源移动操作,避免深拷贝
  ...
  return *this;
}


When called, std::move() can be used to convert the a on the left to an rvalue reference:

a = std::move(a) + b;


In this way, you can avoid deep copying of the a on the right, thus improving performance.