想了解C++的copy/move构造函数和赋值运算符,先举个代码例子:
标题:
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;
}
现在的问题是:如果 this= =&其他
?因为它是一个构造函数,不可能与其他的相等。并且是否需要在 copy
和 move
构造函数中我们delete
(释放)内存?因为内存还没有分配,那为什么要删除呢?我这样说是因为我在很多C++教程中看到他们删除内存并检查是否相等。
所以如果我是对的,那么copy
和move
构造函数可以这样写:
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;
}
还有如何检查移动
赋值中的相等性?
Person &Person::operator=(Person &&other) noexcept
谢谢!
最佳答案
I want to know about C++ copy/move constructor and equal operator...
我认为您指的是赋值运算符 operator=
。等于运算符将是 operator==
。
Does it really need in the copy and move constructors that we check for equality if this==&other?
不,您已经说过不需要这个。
Does it need that in the copy and move constructors we delete (free) the memory?
您将在移动和复制分配中需要它,因为您必须释放旧内存才能复制(或仅设置指针)另一个Person
的内存。您的构造函数不需要删除。
So if I am right, then the copy and move constructor can be written like this
是的,这些都是正确的。您确定要为每个人固定 100 个字节吗?
And also how about checking for equality in move assignment?
我不会检查移动分配中的相等性,因为移动是一种非常便宜的操作,而且您不太可能分配相同的对象。
关于C++ 复制/移动构造函数和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090421/