我想了解C ++复制/移动构造函数和赋值运算符,让我们首先给出代码示例:
标头:
class Person
{
public:
Person();
Person(const char * name, int age);
Person(const Person &person);
Person(Person&&) noexcept;
virtual ~Person();
Person &operator=(const Person & other);
Person &operator=(Person &&other) noexcept;
char *getName() const;
int getAge() const;
private:
char *name;
int age = 0;
};
资源:
Person::Person() : age(0)
{
this->name = new char[100];
memset(this->name, 0, sizeof(char)*100);
}
Person::Person(const char * name, int age) : Person()
{
std::strcpy(this->name, name);
this->age = age;
}
Person::Person(const Person &person)
{
if(this == &person)
{
return;
}
//delete[](name);
this->name = new char[100];
memset(this->name, 0, sizeof(char)*100);
std::strcpy(name, person.name);
age = person.age;
}
Person::Person(Person &&other) noexcept
{
if(this == &other)
{
return;
}
//delete[](name);
name = other.name;
age = other.age;
other.name = nullptr;
other.age = 0;
}
Person &Person::operator=(const Person &other)
{
if(this == &other)
{
return *this;
}
delete[](name);
name = new char[100];
memset(name, 0, sizeof(char)*100);
std::strcpy(name, other.name);
age = other.age;
return *this;
}
Person &Person::operator=(Person &&other) noexcept
{
if(this == &other)
{
return *this;
}
delete[](name);
name = other.name;
age = other.age;
other.name = nullptr;
other.age = 0;
return *this;
}
Person::~Person() {
delete[](name);
name = nullptr;
}
现在的问题是:是否真的需要在copy
andmove
构造函数中检查是否相等this==&other
?因为它是构造函数,所以不可能与其他函数相等。并且还需要在copy
和move
构造函数中我们delete
(释放)内存吗?由于尚未分配内存,为什么需要删除它?我之所以这样说,是因为我在许多C ++教程中看到他们删除了内存并检查是否相等。
因此,如果我是对的,那么copy
andmove
构造函数可以这样写:
Person::Person(const Person &person) : Person()
{
std::strcpy(name, person.name);
age = person.age;
}
Person::Person(Person &&other) noexcept
{
name = other.name;
age = other.age;
other.name = nullptr;
other.age = 0;
}
还有,检查move
分配是否相等?
Person &Person::operator=(Person &&other) noexcept
谢谢!
我想了解C ++复制/移动构造函数和相等运算符...
我认为您是指赋值运算符operator=
。等于运算符为operator==
。
如果this ==&other,它真的需要在复制和移动构造函数中检查是否相等吗?
不,您不需要像已经说明的那样。
是否需要在复制和移动构造函数中删除(释放)内存?
您需要在移动和复制分配中使用它,因为必须释放旧的内存才能复制(或只是将指针设置到)另一个的内存Person
。您的构造函数不需要删除。
所以如果我是对的,那么复制和移动构造函数可以这样写
是的,这些是正确的。您确定真的要为每个人固定100个字节吗?
另外,检查移动分配是否相等?
我不会在移动分配中检查是否相等,因为移动是一项非常便宜的操作,并且您不太可能分配相同的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句