I have an old factory implementation in c++, and I want to use unique pointers instead of raw pointers in it. A minimal example of my code is as follows. I have a base class A, and a derived class B. In main(), I pass 1 to the create method in A, and the type of b1 is now changed to B.
#include <iostream>
#include <map>
class A {
public:
A() {}
virtual void Foo() {}
std::map<int, A *> ®isterType() {
static std::map<int, A *> map_instance;
return map_instance;
}
A *create(int n) { return registerType()[n]; }
};
class B : A {
public:
B() { registerType()[1] = this; }
void Foo() { std::cout << "I am B!\n"; }
};
static B b0;
int main() {
A *b1 = new A();
b1 = b1->create(1);
b1->Foo();
return 0;
}
Now if I want to change raw pointers to unique pointers, I naturally get a collection of errors (the following code results in errors):
#include <iostream>
#include <map>
#include <memory>
class A {
public:
A() {}
virtual void Foo() {}
std::map<int, std::unique_ptr<A>> ®isterType() {
static std::map<int, std::unique_ptr<A>> map_instance;
return map_instance;
}
std::unique_ptr<A> create(int n) { return registerType()[n]; }
};
class B : A {
public:
B() { registerType()[1](this); }
void Foo() { std::cout << "I am B too!\n"; }
};
static B b0;
int main() {
std::unique_ptr<A> b1(new A());
b1 = b1->create(1);
b1->Foo();
return 0;
}
The errors are:
In member function 'std::unique_ptr<A> A::create(int)':
use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]'
std::unique_ptr<A> create(int n) { return registerType()[n]; }
In constructor 'B::B()':
no match for call to '(std::map<int, std::unique_ptr<A> >::mapped_type {aka std::unique_ptr<A>}) (B* const)'
B() { registerType()[1](this); }
^
So I want to know:
- Were unique pointers intended to be used in cases like mine? (I assume the response should be yes!)
- I need to pass
thisas aunique_ptrtype to theregisterTypemethod. How I can pass the ownership of the pointer to the current instance (thiskeyword) to aunique_ptr? (If it is possible or was intended to be possible.) - If it is a good practice to use unique pointers here, how I should implement it?