Skip to content

shared_ptr Derived types cannot be implicitly cast to the share_ptr Base types with gsl::not_null #1187

@daltairwalter

Description

@daltairwalter

Describe the bug
When I try to change function A to return a gsl::not_null<std::shared_ptr> instead of std::shared_ptr, it causes problems in function B that returns the result of function A as a std::shared_ptr

To Reproduce

#include <gsl>
#include <memory>

class Base
{
};

class Derived : public Base
{
};

gsl::not_null<std::shared_ptr<Derived>> A()
{
    return std::make_shared<Derived>();
}

std::shared_ptr<Base> B()
{
    // this fails to compile after the result of A was changed to a not_null
    return A();
}
// your repro here: ...

Expected behavior
I expect the code above to compile and work exactly the same with or without the gsl::not_null

Spec (please complete the following information):

  • OS: Windows
    Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29335 for x64
    All C++ versions

Additional context
Changing the implicit conversion operator:

    constexpr operator T() const { return get(); }

To a templatized version seems to fix this issue:

    template <typename RESULT_TYPE,
              typename = std::enable_if_t<
                      std::is_convertible<T, RESULT_TYPE>::value>>
    operator RESULT_TYPE() const
    {
        return get();
    }

Metadata

Metadata

Assignees

Labels

Status: BlockedCannot proceed due to external factorsStatus: OpenNeeds attentionType: BugIndicates a bug or error

Type

Projects

Status

New

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions