Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on Smart pointer with custom deleter with 'using pointer = <pointer type>'

Parent

Smart pointer with custom deleter with 'using pointer = '

+1
−0

To manage libmagic's magic_t aka magic_set* cookie with a unique_ptr and a custom deleter in a RAII wrapper, I have:

struct MagicDeleter {

    // magic_t is already a pointer (magic_set*)
    using pointer = magic_t;

    void operator()(magic_t cookie) noexcept {
        if (cookie) magic_close(cookie);
    }
};

using unique_magic_ptr = std::unique_ptr<magic_t, MagicDeleter>;

and then initialize and use it like:

m_cookie {unique_magic_ptr(magic_open(MAGIC_MIME_TYPE))};

magic_load(m_cookie.get(), nullptr);

This works fine and valgrind says all is good.

Since magic_t is a pointer already, and I don't think I can or should use magic_set, without using pointer = magic_t, I get errors like:

cannot convert argument of incomplete type 'magic_t' (aka 'magic_set *') to 'pointer' (aka 'magic_set **') for 1st argument

Do I understand correctly, that using pointer = magic_t informs unique_ptr "indirectly" via the deleter, that the pointer to be managed actually is magic_t? Is this a valid way to do?

History

0 comment threads

Post
+2
−0

Your understanding is correct: if the deleter has a member type pointer, then std::unique_ptr uses that to define its own member type pointer, and from that, most other operations. So long as you don’t do anything too complicated, it should “work”. Since you only seem to be doing sets and gets… then, yeah, it shouldn’t be a problem.

But is it a good idea? I would say no.

Try this:

using unique_float_ptr = std::unique_ptr<float>;
using unique_magic_ptr = std::unique_ptr<magic_t, MagicDeleter>;

static_assert(
    not std::same_as<
        unique_float_ptr::element_type,
        unique_float_ptr::pointer
    >
);
static_assert(
    not std::same_as<
        unique_magic_ptr::element_type,
        unique_magic_ptr::pointer
    >
);

As you can see, you’ve kinda warped the abstraction. element_type and pointer should not be the same in a unique_ptr; that just breaks the model.

If magic_t is an opaque handle type, and you don’t want to crack it apart to its constituent types, you can still do this:

struct MagicDeleter
{
    using pointer = ::magic_t;

    void operator()(pointer cookie) noexcept
    {
        if (cookie)
            ::magic_close(cookie);
    }
};

using unique_magic_ptr = std::unique_ptr<std::remove_pointer_t<::magic_t>, MagicDeleter>;

If magic_t really is a pointer, then the unique pointer will be “normal”. If it is not, then it will still “work”, but will have the weird behaviour that element_type and pointer are the same… but that can’t be helped if magic_t really is opaque. In that case, it probably shouldn’t be in a unique_ptr… because it’s not a pointer.


If I were going to use something like libmagic in a C++ program, I would wrap the C interface in a proper C++ interface, like so:

namespace magic {

struct deleter
{
    auto operator()(::magic_t p) const noexcept
    {
        if (p)
            ::magic_close(p);
    }

    // Any other types in the library that need a release function...
    auto operator()(::magic_other_t p) const noexcept
    {
        // ...
    }
};

// Good for a start, if `::magic_t` really is a pointer. If not, then
// a custom wrapper should be used.
//
// A custom wrapper should probably be used in the long run in any case
// for even more safety and power.
//
// For example, in the long run, instead of:
//  ::magic_load(m_cookie.get(), nullptr)
// or even: 
//  load(m_cookie)
// we might prefer:
//  m_cookie.load()
using magic_t = std::unique_ptr<std::remove_pointer_t<::magic_t>, deleter>;

enum class open_flags : int
{
    none,
    mime_type,
    // ... etc. ...
};

auto open(int flags) -> magic_t; // legacy function
auto open(open_flags) -> magic_t;

// Not necessary, but helpful when porting legacy code:
auto close(magic_t& m)
{
    m.reset();
}

auto load(magic_t& m) -> void;
auto load(magic_t& m, std::filesystem::path const&) -> void;
// legacy functions:
auto load(magic_t& m, std::nullptr_t) -> int;
auto load(magic_t& m, char const*) -> int;

} // namespace magic

Then you could start with C-ish code like:

auto m = ::magic_open(MAGIC_MIME_TYPE);
if (not m)
    throw error{};

if (::magic_load(m, nullptr) == -1)
{
    ::magic_close(m);
    throw error{};
}

::magic_close(m);

… and gradually change it like so:

auto m = magic::open(MAGIC_MIME_TYPE);
if (not m)          // this is now unnecessary, because open throws
    throw error{};  // on failure, but it's harmless

if (magic::load(m, nullptr) == -1)  // the if, the check, and the
{                                   // error block are now unnecessary
    magic::close(m);                // but harmless for now
    throw error{};
}

magic::close(m); // unnecessary:

… and then eventually start removing the unnecessary code to get:

auto m = open(magic::open_flags::mime_type);

load(m);

… where everything is strongly-typed, and “smart”, and errors become impossible to miss or ignore.

By making the new, better C++ interface mostly track the original C interface, you can make adoption gradual. And one of the keys to doing that is to make sure that abstractions line up. In particular, the “new” magic_t should not be a (unique) pointer to a magic_t, it should be a magic_t (even if it happens to be a (unique) pointer to something (to whatever the original magic_t points to) as an implementation detail).

History

1 comment thread

Very nice, thank you for your comprehensive answer! Since `magict` is a pointer, for now I went for ... (3 comments)
Very nice, thank you for your comprehensive answer! Since `magict` is a pointer, for now I went for ...
dode‭ wrote 12 days ago

Very nice, thank you for your comprehensive answer! Since magic_t is a pointer, for now I went for your "If magic_t really is a pointer..." solution. I have some homework to do to really understand the difference to what I did. Your "I would wrap the C interface in a proper C++ interface..." solution is still too advanced for me - I am still new to C++...

Indi‭ wrote 11 days ago

Yes, wrapping a C library is not worth it if you’re just using it once, and the project is relatively small. For those cases, what you’re doing—just wrapping the resource management stuff in smart pointers—is exactly the right thing to do.

If you are using the C library a lot, or it’s a more complex project, wrapping pays off massively. You can see that even in the simple case in the answer: it went from 7 lines to 2, and all branches were eliminated. Learning to wrap C libraries well is a really useful skill, that you can learn best by practice. You should try it sometime.

But eh, there’s no rush. As you can see, wrapping a C library does take a lot of code. It’s something that can be done gradually, but it’s a whole project unto itself.

So if your code works now, then it’s good. Always better to get a project working than to make the code “perfect”.

dode‭ wrote 10 days ago

I will for sure try it sometime! For now I have a compromise - a simple wrapper exposing just that one function I need. It is magic.cppm and magic.cpp, used here