문제

I have a class with std::unique_ptr members which are initially initialized to nullptr and later assigned an actual object. They also use custom deleters.

I have two questions regarding this scenario: Should I use std::unique_ptr::reset() or copy assignment operator to assign a value to a unique pointer which was first initialized to nullptr? And if the latter is the case, then how can I make the code below work?

class MyClass {
private:
    std::unique_ptr<Foo, void(*)(Foo*)> m_foo;
    std::unique_ptr<Bar, void(*)(Bar*)> m_bar;
}

MyClass::MyClass() : m_foo(nullptr, ReleaseFoo), m_bar(nullptr, ReleaseBar) { }

bool MyClass::init()
{
    m_foo.reset(CreateFoo()); // works ok
    m_bar = std::unique_ptr<Bar, ReleaseBar>(CreateBar()); // 'ReleaseBar' is not a valid template type argument for parameter '_Dx'
}

Also, would the answer change if no custom deleters were involved (i.e. use reset with custom deleters and copy assignment otherwise)?

도움이 되었습니까?

해결책

You can use resetor the move assignment operator to assign a new value.

The problem with your statement

m_bar = std::unique_ptr<Bar, ReleaseBar>(CreateBar()); // 'ReleaseBar' is not a valid template type argument for parameter '_Dx'

is, as the error message you quote indicates, that ReleaseBar is not a valid template argument. Earlier code uses ReleaseBar in a way consistent with this being a function name. In the earlier code the corresponding template argument was void(*)(Bar*).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top