Skip to content

Custom owning pointer #605

@YannickJadoul

Description

@YannickJadoul

I find myself unable to create and register a smart pointer that would have the same basic functionality as std::unique_ptr. A returned smart pointer does not seem to be moved, and instead another one is created on the same raw pointer.

A small example:

#include <pybind11/pybind11.h>
#include <iostream>
#include "my_unique_ptr.h"

PYBIND11_DECLARE_HOLDER_TYPE(T, my_unique_ptr<T>);

namespace py = pybind11;

class A
{
public:
	A() { std::cout << "A::A() - " << (void *) this << std::endl; }
	~A() { std::cout << "A::~A() - " << (void *) this << std::endl; }
};

PYBIND11_PLUGIN(test) {
    py::module m("test");

    py::class_<A, my_unique_ptr<A>>(m, "A")
    	.def_static("make", [] () { return my_unique_ptr<A>(new A); });


    return m.ptr();
}

where my_unique_ptr.h is a copy of the GCC std::unique_ptr implementation, just to be sure there is nothing wrong with the actual smart pointer type I need to wrap: https://gist.github.com/YannickJadoul/fe5b318e9cbbd65a6e31ead7bad1599f (Please note that in my actual project, I am wrapping existing code by someone else, and there is not an obvious way of changing the custom smart pointer for a standard std::unique_ptr, although I certainly agree that could be infinitely better.)

As running test.A.make() results in the following output ...

A::A() - 0x28ec190
A::~A() - 0x28ec190
<parselmouth.A object at 0x7f1838361de0>

... you can see how quitting my Python interpreter afterwards results in a beautiful segfault.

So, am I misusing this nice pybind11 project and its smart pointers, or is this an unforeseen feature (aka bug)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions