Can I call a virtual destructor using a function pointer? - c++

I have class Data which can hold a pointer to an object. I want to be able to call its destructor manually later on, for which I need its address stored in a variable but it seems that taking the address of constructor/destructor is forbidden. Is there any way around this ?
struct Data {
union {
long i;
float f;
void* data_ptr;
} _data;
std::type_index _typeIndex;
void (*_destructor_ptr)();
template<typename T>
void Init() {
if constexpr (std::is_integral<T>::value) {
//
}
else if constexpr (std::is_floating_point<T>::value) {
//
}
else {
_data.data_ptr = new T;
_typeIndex = std::type_index(typeid(T));
_destructor_ptr = &T::~T; // << -- can't do this
}
}

Store a lambda, suitably converted:
void (*_destructor_ptr)(void *v);
// ...
_destructor_ptr = [](void* v) { delete static_cast<T*>(v); };
Note that you must pass _data.data_ptr for v. If you intend to store a plain function pointer, the lambda may not capture or implicitly refer to _data.data_ptr.

There's also this solution if your compiler doesn't support lambdas:
template<typename T>
struct DestructorHelper {
static void Destroy(void * v) {
delete static_cast<T*>(v);
}
};
and use it as:
_destructor_ptr = &DestructorHelper<T>::Destroy;

I'll also add a solution for smart pointers:
template <class T>
struct DataPtrDeleter
{
void operator()(void * p) { delete (T*)p; }
}
std::shared_ptr<void*> data_ptr(new T, DataPtrDeleter<T>());
//or
std::unique_ptr<void*, DataPtrDeleter<T>> data_ptr(new T, DataPtrDeleter<T>());

Related

What is the best practice to consume a pointer returned as an argument

Normally when a pointer to an object is created and returned from a function you consume it using unique_ptr to ensure it is deleted at the end of the scope.
CustomType* GetTheObject(); // Let's say this the function signature and it returns a new object
void Main() {
auto object = make_unique(GetTheObject());
object->DoSomething();
// Then the object is deleted automatically
}
What if the function signature is like this
bool GetTheObject(CustomType** object);
I can imagine a rather verbose way to consume it
void Main() {
// Declare a pointer which we never need
CustomType* object_ptr;
if(GetTheObject(&object_ptr)) {
// Then create a unique_ptr out of it
auto object = make_unique(object_ptr);
object->DoSomething();
// Then the object is deleted automatically
}
}
Is there a better recommended way how to consume an object in this case. I can think about another let's say unique_ptr2 class which implements & operator and then use it like
unique_ptr2 object;
if(GetTheObject(&object)) {
// use it
}
Is there a ready to be used implementation of unique_ptr2 which would allow doing that? It still feel to be not ideal. Is there a better way?
I might be tempted to write code that automates the conversion to/from the unique ptr. We generate a new function from our existing function "automatically" that has the same signature, but T* return values are unique_ptr<T> and T** arguments are unique_ptr<T>* arguments.
Then we inject the conversion boilerplate using RAII and template metaprogramming.
A ptr_filler is a RAII type that converts a unique_ptr<T>* into a T**:
template<class T>
struct ptr_filler {
std::unique_ptr<T>* output = nullptr;
T* temporary = nullptr;
ptr_filler( std::unique_ptr<T>* bind ):output(bind) {}
operator T**()&&{return &temporary;}
~ptr_filler() {
if (temporary)
*output = std::unique_ptr<T>(temporary);
}
};
ret_converter_t does a type conversion from the C-style API to a C++ unique-ptr API:
template<class T> struct ret_converter { using type=T; };
template<class T> using ret_converter_t = typename ret_converter<T>::type;
template<class T> struct ret_converter<T*> { using type=std::unique_ptr<T>; };
get_converter_t converts argument types from the C-style API, to one that fills unique ptrs via a ptr_filler:
template<class T> struct get_converter { using type=T; };
template<class T> using get_converter_t = typename get_converter<T>::type;
template<class T> struct get_converter<T**> { using type=ptr_filler<T>; };
Finally, call deduces its arguments from the function pointer you pass it, then converts the arguments and retval to use unique ptr memory management, and calls the function f for you:
template<class R, class...Args>
ret_converter_t<R> call( R(* f)(Args...), get_converter_t<Args>... args ) {
return static_cast<ret_converter_t<R>>( f( std::forward<decltype(args)>(args)... ) );
}
now we can:
struct CustomType {
int x;
};
CustomType* GetTheObject(int x) { return new CustomType{x}; }
bool MakeTheObject( CustomType** pp, int a, int b ) { *pp = new CustomType{a+b}; return a>b; }
we can do:
int main() {
std::unique_ptr<CustomType> ptr;
std::cout << call( MakeTheObject, &ptr, 2, 1 ) << " = 1\n";
std::cout << ptr->x << " = 3\n";
ptr = call( GetTheObject, 7 );
std::cout << ptr->x << " = 7\n";
}
You can get fancier with call<MakeTheObject> syntax, but it takes work. This assumes that the API you are wrapping is an C-ish API but returns new'd objects.
Live example.
I would think that returning a std::unique_ptr would be safer than returning a raw pointer, since returning a raw pointer risks the calling code accidentally leaking the object. I'd recommend doing it this way:
#include <iostream>
#include <memory>
class CustomType
{
// ...
};
std::unique_ptr<CustomType> GetTheObject()
{
if ((rand()%2) != 0) return std::make_unique<CustomType>();
return std::unique_ptr<CustomType>(); // nothing to return, sorry
}
int main(int argc, char ** argv)
{
if (std::unique_ptr<CustomType> p = GetTheObject())
{
std::cout << "Got the object!" << std::endl;
}
return 0;
}
If you have to live with an existing function that you don't like the shape of and can't change, you can hide the ugliness inside a wrapper function and then call the wrapper function instead:
std::unique_ptr<CustomType> PrettyGetTheObject()
{
CustomObject * obj;
if (GetTheObject(&obj)) return std::unique_ptr<CustomObject>(obj);
return std::unique_ptr<CustomType>(); // nothing to return, sorry
}
A possible approach is to use a wrapper function. Example:
bool GetOriginal(char **pptr);
bool GetWrapped(std::unique_ptr<char> * puptr) {
bool result;
if (puptr != nullptr) {
char * cptr;
result = GetOriginal(&cptr);
*puptr = std::make_unique(cptr);
} else {
result = GetOriginal(nullptr);
}
return result;
}
This assumes the commonly used pattern of passing null to avoid getting a pointer to manage (e.g. if you're only interested in the return value).
If passing null to the original function is not part of its api, then you could of course use a reference to a std::unique_ptr instead of a raw pointer.
If you have many such functions you could also write a general wrapper function for that, of course:
template<typename Fn, typename T>
bool wrap(Fn fn, std::unique_ptr<T> * puptr) {
bool result;
if (puptr != nullptr) {
T * cptr = nullptr;
result = fn(&cptr);
*puptr = std::make_unique(cptr);
} else {
result = fn(nullptr);
}
return result;
}
// usage: wrap(GetOriginal, &some_unique_ptr)
If the original function takes more arguments, then use std::bind or a lambda.

Merging a C struct factory function with its corresponding C++ wrapping class constructor

Consider writing a C++ wrapper for a C library with the following (T is some other type):
typedef struct { /*fields*/ } S;
S* alloc_S(const T*);
void free_S(S*);
I want to write a class class_S inheriting from S so that calls to alloc_S and free_S are hidden away thanks to, respectively, class_S::class_S(const T*) and class_S::~class_S() (removing the risk of forgetting a call to free_S).
As alloc_S already allocates and assigns values to all the fields of the structure it returns, is there an elegant way to build the rest of the class_S object "around" that structure?
My goal is to avoid the overhead (in time and space) of something like
class_S::class_S(const T* t)
{
S* tmp = alloc_S(t);
// deep-copy tmp into this
free_S(tmp);
}
Obviously, instead of inheriting from S, I could write class_S to have a S* member and work with it but, if possible, I would like to avoid this approach.
Here's one non-standard, confusing and unmaintainable way - note the special construction syntax
#include <memory>
extern "C" {
struct T {};
struct S
{
};
S* alloc_S(T*);
void free_S(S*);
}
struct class_S : S
{
void * operator new (std::size_t, T* p)
{
return alloc_S(p);
}
void operator delete(void *p)
{
if (p) free_S(reinterpret_cast<S*>(p));
}
};
int main()
{
T t;
auto ps = new (&t) class_S;
delete ps;
}
On balance you're probably better off using a unique_ptr with custom deleter:
struct class_S
{
struct deleter {
void operator()(S*p) const noexcept {
free_S(p);
}
};
class_S(T* p) : impl_(alloc_S(p), deleter()) {}
// add proxy methods as required
std::unique_ptr<S, deleter> impl_;
};
int main()
{
T t;
auto mys = class_S(&t);
}

Non-copying std::shared_ptr<boost::any>?

I store "instances of different types" with "shared ownership". That's what I currently do:
class Destructible {
public:
virtual ~Destructible() = default;
};
// UGLY
class MyType1 : public Destructible { ... };
class MyTypeN : public Destructible { ... };
class Storage {
std::vector<std::shared_ptr<Destructible>> objects_;
...
}
I'd love to switch to boost::any, removing all these conformances and gaining the ability to store instances of truly any type. Also I like boost::any interface and boost::any_cast.
But my types don't satisfy ValueType requirements, they are not copyable. What is the best (preferably existing) solution for this problem? Something like shared_any_ptr, which captures destructor at creation, has type erasure, reference counter and can do any_cast.
Edit: boost::any allows creation with move, but I'd prefer not to even move and use pointers.
Edit2: I also use make_shared extensively, so something make_shared_any_ptr would come in handy.
This isn't tricky with shared pointers. We can even avoid multiple allocations.
struct any_block {
any_block(any_block const&)=delete;
template<class T>
T* try_get() {
if (!info || !ptr) return nullptr;
if (std::type_index(typeid(T)) != std::type_index(*info)) return nullptr;
return static_cast<T*>(ptr);
}
template<class T>
T const* try_get() const {
if (!info || !ptr) return nullptr;
if (std::type_index(typeid(T)) != std::type_index(*info)) return nullptr;
return static_cast<T const*>(ptr);
}
~any_block() {
cleanup();
}
protected:
void cleanup(){
if (dtor) dtor(this);
dtor=0;
}
any_block() {}
std::type_info const* info = nullptr;
void* ptr = nullptr;
void(*dtor)(any_block*) = nullptr;
};
template<class T>
struct any_block_made:any_block {
std::aligned_storage_t<sizeof(T), alignof(T)> data;
any_block_made() {}
~any_block_made() {}
T* get_unsafe() {
return static_cast<T*>((void*)&data);
}
template<class...Args>
void emplace(Args&&...args) {
ptr = ::new((void*)get_unsafe()) T(std::forward<Args>(args)...);
info = &typeid(T);
dtor = [](any_block* self){
static_cast<any_block_made<T>*>(self)->get_unsafe()->~T();
};
}
};
template<class D>
struct any_block_dtor:any_block {
std::aligned_storage_t<sizeof(D), alignof(D)> dtor_data;
any_block_dtor() {}
~any_block_dtor() {
cleanup();
if (info) dtor_unsafe()->~D();
}
D* dtor_unsafe() {
return static_cast<D*>((void*)&dtor_data);
}
template<class T, class D0>
void init(T* t, D0&& d) {
::new( (void*)dtor_unsafe() ) D(std::forward<D0>(d));
info = &typeid(T);
ptr = t;
dtor = [](any_block* s) {
auto* self = static_cast<any_block_dtor<D>*>(s);
(*self->dtor_unsafe())( static_cast<T*>(self->ptr) );
};
}
};
using any_ptr = std::shared_ptr<any_block>;
template<class T, class...Args>
any_ptr
make_any_ptr(Args&&...args) {
auto r = std::make_shared<any_block_made<T>>();
if (!r) return nullptr;
r->emplace(std::forward<Args>(args)...);
return r;
}
template<class T, class D=std::default_delete<T>>
any_ptr wrap_any_ptr( T* t, D&& d = {} ) {
auto r = std::make_shared<any_block_dtor<std::decay_t<D>>>();
if (!r) return nullptr;
r->init( t, std::forward<D>(d) );
return r;
}
you'd have to implement any_cast, but with try_get<T> it should be easy.
There may be some corner cases like const T that the above doesn't handle.
template<class T>
std::shared_ptr<T>
crystalize_any_ptr( any_ptr ptr ) {
if (!ptr) return nullptr;
T* pt = ptr->try_get<T>();
if (!pt) return nullptr;
return {pt, ptr}; // aliasing constructor
}
This lets you take a any_ptr and turn it into a shared_ptr<T> if the types match without copying anything.
live example.
You'll notice how similar any_block_made and any_block_dtor is. I believe that this is why at least one major shared_ptr in a std library reuses the spot the deleter lives in for make_shared itself.
I could probably do similar, and reduce binary size here. In addition, the T/D parameter of any_block_made and any_block_dtor is really just about how big and aligned the block of memory we play with is, and what exactly type erasued helper I store in the dtor pointer in the parent. A compiler/linker with COMDAT folding (MSVC or GOLD) may eliminate the binary bloat here, but with a bit of care I could do it myself.

Bypass a template error with a private destructor

In compile time, I've got the following issue, how to make this compile, because conceptually for me it's correct, any suggestions of refactoring are welcome.
I got a compile error because "Search" destructor is private but I won't use delete on a Search pointer since I provided a custom Deleter in the initialization of the base class. I know that the compiler doesn't know that, how to bypass it.
error description :
error C2248: cannot access private member declared in class 'Search'
compiler has generated 'Search::~Search' here
class Search
{
public:
static Search* New(/* */); // using a pool of already allocated objects to avoid expensive allocations
static void Delete(Search*);
private:
Search(/* */) {/* */}
~Search() {/* */}
};
template<class T>
class MyList
{
public:
typedef (*CustomDeleter) (T* pElement);
MyList(CustomDeleter lpfnDeleter = NULL) {};
void Empty()
{
for (/**/)
{
if (m_pList[m_nListLastUsed])
{
if (m_lpfnCustomDeleter == NULL)
delete m_pList[m_nListLastUsed]; // COMPILE ERROR HERE BECAUSE Search destructor is private BUT I won't use that instruction since
// I provided a custom Deletern I know that the compiler doesn't know that, how to bypass it
else
m_lpfnCustomDeleter(m_pList[m_nListLastUsed]);
}
}
}
private:
T** m_pList;
CustomDeleter m_lpfnCustomDeleter; // Pointer to a custom deleter
};
class Query : public MyList<Search>
{
public:
Query() : MyList<Search>(&Search::Delete) // I set a custom deleter since Search hides its destructor : is this the right way ?
{}
~Query()
{
/****/
Empty(); // PROBLEM HERE
/***/
}
};
Make sure that 'm_lpfnCustomDeleter' is never NULL or better nullptr. You can make sure of this by falling back to a default 'deleter' if the user does not provide with any custom deleter.
I would prefer something like below.
#include <iostream>
template <typename PointerType>
struct DefaultDeleter {
void operator()(PointerType* ptr) {
std::cout << "Delete\n";
}
};
struct CustomDeleter {
void operator()(int* ptr) {
std::cout << "Custom int deleter" << std::endl;
}
};
template <typename T, typename Deleter = DefaultDeleter<T>>
class Whatever
{
public:
Whatever() {
std::cout << "Cons\n";
}
void deinit() {
Deleter d;
auto v = new T;
d(v); // Just for the sake of example
}
};
int main() {
Whatever<char> w;
w.deinit();
Whatever<int, CustomDeleter> w2;
w2.deinit();
return 0;
}
Updated :: W/o code refactoring
Assuming w/o c++11
Have this small metaprogram added to your code base.
namespace my {
template <typename T, typename U> struct is_same {
static const bool value = false;
};
template <typename T>
struct is_same<T, T> {
static const bool value = true;
};
template <bool v, typename T = void> struct enable_if;
template <typename T = void> struct<true, T> {
typedef T type;
};
}
Change your Empty function to:
void Empty() {
for (/****/) {
do_delete();
}
}
template <typename =
typename my::enable_if<my::is_same<T, Search>::value>::type>
void do_delete() {
assert (m_lpfnCustomDeleter != NULL);
m_lpfnCustomDeleter(m_pList[m_nListLastUsed]);
}
void do_delete() {
delete m_pList[m_nListLastUsed];
}
If you are using c++11, the you dont have to write the metaprogram under namespace 'my'. Just replace 'my::is_same' and 'my::enable_if' with 'std::is_same' and 'std::enable_if'.
Note:, Have not compiled and tested the above code.
Separate the code doing the deleting from the rest:
if (m_pList[m_nListLastUsed])
{
if (m_lpfnCustomDeleter == NULL)
delete m_pList[m_nListLastUsed]; // COMPILE ERROR HERE BECAUSE Search destructor is private BUT I won't use that instruction since
// I provided a custom Deletern I know that the compiler doesn't know that, how to bypass it
else
m_lpfnCustomDeleter(m_pList[m_nListLastUsed]);
}
Replace the code above by a call to:
custom_delete(m_pList[m_nListLastUsed]);
Then add it as a method of your list class, don't forget to include <type_traits> as well:
std::enabled_if<std::is_destructible<T>::value, void>::type custom_delete(T* ptr) {
/* Note: this isn't pre-2000 anymore, 'lpfn' as a prefix is horrible,
don't use prefixes! */
if (m_lpfnCustomDeleter) {
m_lpfnCustomDeleter(ptr);
} else {
delete ptr;
}
}
std::enabled_if<!std::is_destructible<T>::value, void>::type custom_delete(T* ptr) {
if (!m_lpfnCustomDeleter) {
throw "No custom deleter for a non destructible type!";
}
m_lpfnCustomDeleter(ptr);
}
enabled_if will make it so that the function where it can delete the object directly doesn't exist in your list if the object has a private destructor.
Alternatively, you could pass a structure (or function) acting as a custom deleter as the second template argument of your list with a default value as one that calls the delete operator, then directly call this structure on your pointer, as in Arunmu's anser.

Copy-construct and later access arbitrary POD types

I'd like to fill in the store() and launch() methods in the below code. The important detail which captures the spirit of the problem is that the object foo declared in main() no longer exists at the time we call launch(). How can I do this?
#include <cstdio>
#include <cstring>
#include <type_traits>
template<typename T, typename U=
typename std::enable_if<std::is_trivially_copyable<T>::value,T>::type>
struct Launchable {
void launch() { /* some code here */ }
T t;
// other members as needed to support DelayedLauncher
};
class DelayedLauncher {
public:
template<typename T>
void store(const Launchable<T>& t) {
// copy-construct/memcpy t into some storage
}
void launch() const {
// call t.launch(), where t is (a copy of) the last value passed into store()
}
// other members as needed
};
int main() {
DelayedLauncher launcher;
{
Launchable<int> foo;
launcher.store(foo);
}
launcher.launch(); // calls foo.launch()
return 0;
}
Note that if we only had a fixed set of N types to pass into store(), we could achieve the desired functionality by declaring N Launchable<T> fields and N non-template store() methods, one for each type, along with an enum field whose value is use in a switch statement in the launch() method. But I'm looking for an implementation of DelayedLauncher that will not need modification as more Launchable types are added.
using std::function:
class DelayedLauncher {
public:
template<typename T>
void store(const Launchable<T>& t) {
f = [t]() {t.launch();};
}
void launch() const { f(); }
private:
std::function<void()> f;
};
You could give Launchable a base class with a virtual launch() and no template, and store pointers to that base class in Launcher::store.
EDIT: Adapted from #dshin's solution:
struct LaunchableBase {
virtual void launch() = 0;
};
template<typename T, typename U=
typename std::enable_if<std::is_trivially_copyable<T>::value,T>::type>
struct Launchable : public LaunchableBase {
virtual void launch() override { /* some code here */ }
T t;
// other members as needed to support DelayedLauncher
};
class DelayedLauncher {
public:
template<typename T>
void store(const Launchable<T>& t) {
static_assert(sizeof(t) <= sizeof(obj_buffer),
"insufficient obj_buffer size");
static_assert(std::is_trivially_destructible<T>::value,
"leak would occur with current impl");
p = new (obj_buffer) Launchable<T>(t);
}
void launch() const {
p->launch();
}
private:
char obj_buffer[1024]; // static_assert inside store() protects us from overflow
LaunchableBase *p;
};
I believe this variant of Jarod42's solution will avoid dynamic allocation, although I would appreciate if someone could confirm that this will work the way I think it will:
class DelayedLauncher {
public:
template<typename T>
void store(const Launchable<T>& t) {
static_assert(sizeof(t) <= sizeof(obj_buffer),
"insufficient obj_buffer size");
static_assert(std::is_trivially_destructible<T>::value,
"leak would occur with current impl");
auto p = new (obj_buffer) Launchable<T>(t);
auto ref = std::ref(*p);
f = [=]() {ref.get().launch();};
}
void launch() const {
f();
}
private:
char obj_buffer[1024]; // static_assert inside store() protects us from overflow
std::function<void()> f;
};
I believe it should work because the resources I've looked at indicate that std::function implementations typically have a "small capture" optimization, only triggering a dynamic allocation if the total size of the captured data exceeds some threshold.
EDIT: I replaced my code with a version provided by Jarod42 in the comments. The standard guarantees the above implementation will not trigger dynamic allocation.