This is an experiment to see if it can be done.
By making destructor private, I'm able to disable direct object creation (ex: Test t; ). I want to force instantiation via new (this works) or smart pointer like unique_ptr.
I believe that I'm doing something wrong with how I'm approaching unique_ptr but I'm not sure what.
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class Test
{
private:
~Test() {cout << "x" << endl;}
public:
Test() {cout << "c" << endl;}
static void destruct(Test* ptr) {delete ptr;}
};
int main()
{
//Perfect
//We want to disable direct creation. This fails and we want it to fail.
//Test t; ERROR: Can't because dest is private!
//OK
Test *ptr = new Test; //Creation via new works fine
ptr->destruct(ptr); //Destruct works fine
//NOT OK. :-(
//auto up = make_unique<Test>(); //error
//unique_ptr<Test> up( new Test(), [](Test* p){destruct(p);} ); //error
return 0;
}
Aucun commentaire:
Enregistrer un commentaire