use implicit conversion of unique_ptr<T, DeleterA> to unique_ptr<const T, DeleterB>

relies on DeleterB being constructible from DeleterA
also uses that T* can always be converted to void* (but not the other way around)
This commit is contained in:
Marco Porsch 2021-12-20 10:31:16 +01:00
parent cf841e10e9
commit 828fc87623
2 changed files with 8 additions and 6 deletions

View File

@ -39,7 +39,8 @@ struct BasicConstraint: Constraint
OwningPointer clone(CustomAlloc allocFn, CustomFree freeFn) const override
{
// smart pointer to automatically free raw memory on exception
auto ptr = std::unique_ptr<void, CustomFree>(allocFn(sizeof(ConstraintType)), freeFn);
typedef std::unique_ptr<Constraint, CustomFree> RawOwningPointer;
auto ptr = RawOwningPointer(static_cast<Constraint*>(allocFn(sizeof(ConstraintType))), freeFn);
if (!ptr) {
throwRuntimeError("Failed to allocate memory for cloned constraint");
}
@ -47,8 +48,8 @@ struct BasicConstraint: Constraint
// constructor might throw but the memory will be taken care of anyways
(void)new (ptr.get()) ConstraintType(*static_cast<const ConstraintType*>(this));
// reassign managed memory to smart pointer that will also destroy object instance
return OwningPointer(static_cast<const Constraint*>(ptr.release()), freeFn);
// implicitly convert to smart pointer that will also destroy object instance
return ptr;
}
protected:

View File

@ -906,7 +906,8 @@ public:
OwningPointer clone(CustomAlloc allocFn, CustomFree freeFn) const override
{
// smart pointer to automatically free raw memory on exception
auto ptr = std::unique_ptr<void, CustomFree>(allocFn(sizeOf()), freeFn);
typedef std::unique_ptr<Constraint, CustomFree> RawOwningPointer;
auto ptr = RawOwningPointer(static_cast<Constraint*>(allocFn(sizeOf())), freeFn);
if (!ptr) {
throwRuntimeError("Failed to allocate memory for cloned constraint");
}
@ -914,8 +915,8 @@ public:
// constructor might throw but the memory will be taken care of anyways
(void)cloneInto(ptr.get());
// reassign managed memory to smart pointer that will also destroy object instance
return OwningPointer(static_cast<const Constraint*>(ptr.release()), freeFn);
// implicitly convert to smart pointer that will also destroy object instance
return ptr;
}
virtual bool validate(const adapters::Adapter &target,