I'm playing with a couple of concepts that I am still rather new to. What I am trying to do is dependency inject a "Screen" object into the private member "TempCtrl::mScreen" using unique pointers. I believe I am implementing the design pattern correctly, but I have never done this with unique pointers and it would seem that the pointer is deleted prior to the TempCtrl constructor call. Why is this happening?
excerpt of Main Function:
#include "tempctrl.hpp"
#include "screen.hpp"
#include <memory>
int main()
{
std::unique_ptr<Screen> _Screen(new Screen);
TempCtrl tc(_Screen);
/* ... */
}
excerpt of TempCtrl constructor declaration:
class TempCtrl
{
public:
TempCtrl(std::unique_ptr<Screen> _Screen);
~TempCtrl();
private:
std::unique_ptr<Screen> mScreen;
};
excerpt of TempCtrl implementaton:
TempCtrl::TempCtrl(std::unique_ptr<Screen> _Screen)
: mScreen(_Screen)
{
}
compiler output:
/usr/bin/g++ -std=c++11 -g -c screen.cpp tempctrl.cpp main.cpp
tempctrl.cpp: In constructor 'TempCtrl::TempCtrl(std::unique_ptr<Screen>)':
tempctrl.cpp:6:18: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Screen; _Dp = std::default_delete<Screen>]'
: mScreen(_Screen)
^
In file included from /usr/include/c++/8/memory:80,
from tempctrl.hpp:14,
from tempctrl.cpp:1:
/usr/include/c++/8/bits/unique_ptr.h:394:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
^~~~~~~~~~
main.cpp: In function 'int main()':
main.cpp:9:22: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Screen; _Dp = std::default_delete<Screen>]'
TempCtrl tc(_Screen);
^
In file included from /usr/include/c++/8/memory:80,
from tempctrl.hpp:14,
from main.cpp:1:
/usr/include/c++/8/bits/unique_ptr.h:394:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
^~~~~~~~~~
In file included from main.cpp:1:
tempctrl.hpp:68:3: note: initializing argument 1 of 'TempCtrl::TempCtrl(std::unique_ptr<Screen>)'
TempCtrl(std::unique_ptr<Screen> _Screen);
^~~~~~~~
make: *** [Makefile:14: *.o] Error 1
Aucun commentaire:
Enregistrer un commentaire