Trouble using std::make_unique with member variable of class

710 Views Asked by At

I have not used std::make_unique before, and code inspection encouraged me to do it.

If I use this, it does not display errors:

auto x = make_unique<CChristianLifeMinistryHtmlView>();

But when I try it with my class member variable CChristianLifeMinistryHtmlView *m_pHtmlPreview it does not like it:

m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();

How do I use std::make_unique with a member variable of the class?

1

There are 1 best solutions below

0
JeJo On BEST ANSWER

Your issue is nothing to do with the class member, rather its type!

std::make_unique() returns std::unique_ptr for the template type T (i.e. std::unique_ptr of an instance of type T)

template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
^^^^^^^^^^^^^^

The member

CChristianLifeMinistryHtmlView *m_pHtmlPreview;

is a pointer to a CChristianLifeMinistryHtmlView, not a std::unique_ptr. Hence, the type mismatch.


How do I use make_unique with a member variable of the class?

Therefore, you need to use std::unique_ptr<CChristianLifeMinistryHtmlView> as the type of the m_pHtmlPreview member:

std::unique_ptr<CChristianLifeMinistryHtmlView> m_pHtmlPreview; 
...
m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();

If it is a long typing, a type alias wouldn't be a bad idea:

using UniqueCLMHView = std::unique_ptr<CChristianLifeMinistryHtmlView>;
UniqueCLMHView m_pHtmlPreview; 
...
m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();