Skip to content

[c++] Consider implementing Drop for types with destructors #1840

Open
@Volker-Weissmann

Description

@Volker-Weissmann

Consider the following C++ code:

#include "stdio.h"
class Inner {
public:
	Inner();
	~Inner();
};
Inner::Inner() {
	printf("constructing Inner\n");
}
Inner::~Inner() {
	printf("destructing Inner\n");
}
class Outer {
	Inner in;
public:
	Outer();
	~Outer();
};
Outer::Outer() {
	printf("constructing Outer\n");
}
Outer::~Outer() {
	printf("destructing Outer\n");
}

If you use bindgen to execute

let mut val = Outer::new();
val.destruct();

You get the output

constructing Inner
constructing Outer
destructing Outer
destructing Inner

Which is also the output of the C++ code

#include "wrapper.cpp"
int main() {
	Outer obj;
}

If we now remove the ~Outer() deconstructor, this C++ code outputs

constructing Inner
constructing Outer
destructing Inner

But the rust code

let mut val = Outer::new();
val.destruct();

no longer compilers because Outer::destruct does not exist and the rust code

let mut val = Outer::new();

just outputs

constructing Inner
constructing Outer

which might result in memory leaks or similar bugs.
A similar problem arises if you remove the default constructor.

Is it possible to automatically add constructors and destructors that call the constructors and destructors of the member variables?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions