class BaseShader {
std::unique_ptr<HandleInterface> handle_;
public:
BaseShader();
BaseShader(std::unique_ptr<HandleInterface> handle_ptr);
.cpp
BaseShader::BaseShader(std::unique_ptr<HandleInterface> handle_ptr) {
handle_.reset(handle_ptr.get());
}
//BaseHandle implements HandleInterface
BaseShader::BaseShader():BaseShader(std::make_shared<BaseHandle>()) {
}
How would I initialize my unique_ptr handle_ correctly?
I want to use it like this BaseShader s(std::make_shared<BaseHandle>());
Clang tells me
error: no matching constructor for initialization of 'BaseShader'
BaseShader::BaseShader():BaseShader(std::make_shared<BaseHandle>()) {
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I probably messed it up.
1.) Is my constructor argument correct? BaseShader::BaseShader(std::unique_ptr<HandleInterface> handle_ptr)
2.) If 1.) is true is handle_.reset(handle_ptr.get()); the correct way of initializing my handle_ unique_ptr?
First of all, you should simply std::move from the argument of the constructor to handle_ in the member initialization list:
BaseShader::BaseShader(std::unique_ptr<HandleInterface> handle_ptr)
: handle_(std::move(handle_ptr))
{ }
Second, std::make_shared will give you a shared_ptr, when you want a unique_ptr. Unfortunately, there is no std::make_unique (yet), so you'll have to do it like this:
BaseShader::BaseShader()
: BaseShader(std::unique_ptr<BaseHandle>(new BaseHandle()))
{ }
This will only work if BaseHandle is derived from HandleInterface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With