I have difficulty understanding std::move behavior and would like to know whether it is necessary to manually call delete for newStudentDan after "addStudent" in an example like below, or it will be a memory leak.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Student {
public:
Student(std::string name): name_{name} {}
void addParent(std::string name) {
parent_ = name;
}
private:
std::string name_;
std::string parent_;
};
class School {
public:
//constructor
School(): name_{"default"} {}
Student* addStudent(Student student);
Student* addStudent(std::unique_ptr<Student>&& ptr, int);
private:
std::string name_;
std::vector<std::unique_ptr<Student>> students_;
};
Student* School::addStudent(Student student) {
return this->addStudent(std::unique_ptr<Student>{ new Student{std::move(student)}}, 1);
}
Student* School::addStudent(std::unique_ptr<Student>&& ptr, int) {
Student* retval{ptr.get()};
students_.push_back(std::move(ptr));
return retval;
}
int main() {
School newSchool;
Student* newStudentDan = new Student("Dan");
newStudentDan->addParent("Lisa");
newSchool.addStudent(*newStudentDan);
//...continues
return 0;
}