I am using visual studio on windows10 using C++.
And I'm learning about pimpl idiom, what confuses me is that if without destructor of employee, compiler would bring out error: can't delete an incomplete type. I don't understand why I need a destructor for employee, isn't it enough having a destructor for struct impl because of unique_ptr.
this is the website which introduce pimpl idiom, it says: "Since std::unique_ptr is a complete type it requires a user-declared destructor and copy/assignment operators in order for the implementation class to be complete." But I still don't understand and didn't get much information about the definition of complete type it says.
https://www.geeksforgeeks.org/pimpl-idiom-in-c-with-examples/
employee.h
#pragma once
#include<iostream>
#include<string>
using std::string;
using std::unique_ptr;
//pimple idiot
namespace employee {
class employee {
public:
employee(const string& s);
//~employee();//if without this line, compiler would bring out error: can't delete an incomplete type
employee(const employee& e);
employee& operator=(employee e);
void setSalary(float s);
float getSalary();
private:
struct impl;
unique_ptr<impl> pimpl;
};
}
employee.cpp
#include"employee.h"
namespace employee {
struct employee::impl {//
impl(const string& s) :name(s),salary(0){}
~impl(){}//for unique_ptr
string name;
float salary;
};
employee::employee(const string& s):pimpl(new impl(s)){
}
//employee::~employee() = default;
employee::employee(const employee& e) : pimpl(new impl(*e.pimpl)) {
}
employee& employee::operator=(employee e) {
std::swap(this->pimpl, e.pimpl);
return *this;
}
void employee::setSalary(float s) {
pimpl->salary = s;
}
float employee::getSalary() {
return pimpl->salary;
}
}