This question already has an answer here:
I am learning C++11 move semantics, and I'm implementing my own class that uses move semantics.
person.h:
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
#include <string>
class Person {
public:
Person();
Person(std::string name, int age);
Person(const Person &obj);
Person(Person &&obj);
~Person();
Person & operator=(Person rhs);
private:
std::string name;
int age;
void swap(Person &obj);
};
#endif
person.cc:
#include <string>
#include "person.h"
Person::Person() {};
Person::Person(std::string name, int age) : name(name), age(age) {
std::cout << "Default constructor called.\n";
}
Person::Person(const Person &obj) {
std::cout << "Copy constructor called.\n";
name = obj.name;
age = obj.age;
}
Person::Person(Person &&obj) {
std::cout << "Move constructor called with: " << obj.name << "\n";
swap(obj);
obj.name.clear();
obj.age = 0;
}
Person & Person::operator=(Person rhs) {
std::cout << "Assignment called.\n";
swap(rhs);
return *this;
}
void Person::swap(Person &obj) {
std::swap(name, obj.name);
std::swap(age, obj.age);
}
Person::~Person() {
name.clear();
age = 0;
}
When I call an rvalue with std::move
, the move constructor is being called. But when called without one, the move constructor is not being called but neither is the copy constructor. In that case, how exactly does the parameter get passed to the assignment parameter rhs
above?
#include <iostream>
#include "person.h"
Person getPerson() {
return Person("Px", 100);
}
int main() {
std::cout << "Regular call:\n";
Person one;
one = getPerson(); // does not print "Move constructor called..."
std::cout << "\n\n";
std::cout << "std::move call:\n";
Person two;
two = std::move(getPerson());
return 0;
}
Stdout:
Regular call:
Default constructor called.
Assignment called.
std::move call:
Default constructor called.
Move constructor called with: Px
Assignment called.
My g++ version (I am compiling with --std=c++11 flag
):
$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Any help is much appreciated. Thank you!
Aucun commentaire:
Enregistrer un commentaire