我正在学习解构器,复制和克隆,因此我编写了这段代码。一切都很清楚,但一行。它是第5行Destructor myClass1 0x28fec0
中的析构函数。它来自哪里,为什么被称为?
控制台输出:
Constructor myClass1 0x28fe98
Constructor myClass2 0x28fe88
Constructor myClass3 0x28fe78
operator=
Destructor myClass1 0x28fec0
clone
Constructor clone 0x28fed0
operator=
Destructor clone 0x28fed0
Destructor myClass3 0x28fe78
Destructor myClass2 0x28fe88
Destructor myClass1 0x28fe98
main.cpp中:
#include <iostream>
#include "MyClass.h"
int main(){
MyClass myClass1("myClass1"), myClass2("myClass2"), myClass3("myClass3");
myClass2 = myClass1;
myClass3 = myClass1.clone();
return 0;
}
MyClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
#include <iostream>
#include <string>
class MyClass{
private:
int *values;
int size;
int *copies;
std::string name;
public:
MyClass();
MyClass(std::string name);
~MyClass();
void operator=(MyClass myClass);
MyClass clone();
};
#endif
MyClass.cpp:
#include "MyClass.h"
MyClass::MyClass(){
std::cout << "Constructor" << this << std::endl;
name = "None";
size = 1;
values = new int[1];
values[0] = 0;
copies = new int;
*copies = 1;
count++;
}
MyClass::MyClass(std::string name){
std::cout << "Constructor " << name << " " << this << std::endl;
size = 1;
values = new int[1];
values[0] = 0;
copies = new int;
*copies = 1;
count++;
this->name = name;
}
MyClass::~MyClass(){
std::cout << "Destructor " << name << " " << this << std::endl;
if(*copies == 1){
delete [] values;
values = 0;
delete copies;
copies = 0;
}
count--;
}
void MyClass::operator=(MyClass myClass){
std::cout << "operator=" << std::endl;
if(*copies == 1){
delete copies;
copies = 0;
delete [] values;
values = 0;
}
size = myClass.size;
values = myClass.values;
copies = myClass.copies;
(*copies)++;
}
MyClass MyClass::clone(){
std::cout << "clone" << std::endl;
MyClass myClass("clone");
myClass.size = size;
delete [] myClass.values;
myClass.values = new int[size];
for(int i = 0; i < size; i++){
myClass.values[i] = values[i];
}
return myClass;
}
答案 0 :(得分:6)
因为您将operator=
的参数作为副本。
因此它会在MyClass
内创建一个operator=
对象,当operator=
返回时会被销毁。
答案 1 :(得分:3)
void MyClass::operator=(MyClass myClass)
按值计算其参数。所以,当你打电话
myClass2 = myClass1;
复制构造函数在myClass1
的{{1}}参数中创建MyClass
的副本。该函数完成后,此副本将被销毁。要查看这种情况,请将print语句放在复制构造函数MyClass::operator=
中。
另外,引用cppreference,类型MyClass::MyClass(const MyClass&)
的赋值运算符的规范重载是
T
这是复制和交换的习惯用语。另请注意,返回类型为T& T::operator=(T arg) { // copy/move constructor is called to construct arg
swap(arg); // resources exchanged between *this and arg
return *this;
} // destructor is called to release the resources formerly held by *this
而非T&
。
答案 2 :(得分:1)
void operator=(MyClass myClass);
应为MyClass& operator=(const MyClass& myClass);
(标准)。此外,您通过副本传递myClass,这意味着创建了一个临时对象....然后销毁。