Created
August 12, 2014 20:36
-
-
Save acmorrow/8866976c6d100229ba10 to your computer and use it in GitHub Desktop.
unique_ptr example for using void*
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef LIBFOO_H_INCLUDED | |
#define LIBFOO_H_INCLUDED | |
#pragma once | |
#include "libfoo_export.h" | |
#if defined(__cplusplus) | |
#define LIBFOO_NOEXCEPT noexcept | |
extern "C" { | |
#else | |
#define LIBFOO_NOEXCEPT | |
#endif | |
typedef struct foo_thing1 { | |
int val; | |
} foo_thing1_t; | |
LIBFOO_API foo_thing1_t* foo_thing1_create() LIBFOO_NOEXCEPT; | |
LIBFOO_API void foo_thing1_destroy(foo_thing1_t* thing1) LIBFOO_NOEXCEPT; | |
typedef struct foo_thing2 { | |
double val; | |
} foo_thing2_t; | |
LIBFOO_API foo_thing2_t* foo_thing2_create(double value1) LIBFOO_NOEXCEPT; | |
LIBFOO_API void foo_thing2_destroy(foo_thing2_t* thing2) LIBFOO_NOEXCEPT; | |
LIBFOO_API void foo_thing2_print(foo_thing2_t const* thing1) LIBFOO_NOEXCEPT; | |
#if defined(__cplusplus) | |
} // extern "C" | |
#endif | |
#endif // LIBFOO_H_INCLUDED | |
class FooThing2 { | |
private: | |
static void dtor(void*); | |
public: | |
using handle = std::unique_ptr<void, decltype(&FooThing2::dtor)>; | |
FooThing2(); | |
void print(); | |
private: | |
handle _handle; | |
}; | |
namespace { | |
foo_thing2* cast(FooThing2::handle& h) { | |
return reinterpret_cast<foo_thing2*>(h.get()); | |
} | |
} | |
FooThing2::FooThing2() | |
: _handle(foo_thing2_create(1.0), &FooThing2::dtor) { | |
} | |
void FooThing2::print() { | |
foo_thing2_print(cast(_handle)); | |
} | |
void FooThing2::dtor(void* arg) { | |
foo_thing2_destroy(static_cast<foo_thing2*>(arg)); | |
} | |
int main(int argc, char* argv[]) { | |
#if 0 | |
libfoo::thing1_t thing1; | |
libfoo::thing2_t thing2_a{0.0}; | |
libfoo::thing2_t thing2_b{42}; | |
thing2_b.value(thing1.value() * thing2_a.value()); | |
assert(thing2_b.value() == 0.0); | |
foo_thing2_print(static_cast<foo_thing2_t*>(thing2_b)); | |
thing2_b.print(); | |
#endif | |
{ | |
FooThing2 magic; | |
FooThing2 more_magic(std::move(magic)); | |
magic.print(); | |
} | |
return EXIT_SUCCESS; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment