Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an unique_ptr though a constructor

Tags:

c++

c++11

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?

like image 634
Maik Klein Avatar asked Apr 21 '26 14:04

Maik Klein


1 Answers

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.

like image 179
Joseph Mansfield Avatar answered Apr 24 '26 02:04

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!