Using a std::shared_ptr expresses shared ownership and optionality (with its possibility to be null).
I find myself in situations where I want to express shared ownership only in my code, and no optionality. When using a shared_ptr as a function parameter I have to let the function check that it is not null to be consistent/safe.
Passing a reference instead of course is an option in many cases, but I sometimes would also like to transfer the ownership, as it is possible with a shared_ptr.
Is there a class to replace shared_ptr without the possibility to be null, some convention to handle this problem, or does my question not make much sense?
You are asking for not_null wrapper class. Fortunately your issue is already addressed by C++ experts guideline and there are already example implementations - like this one. Search for not_null class template.
You could write a wrapper around std::shared_ptr that only allows creation from non-null:
#include <memory>
#include <cassert>
template <typename T>
class shared_reference
{
std::shared_ptr<T> m_ptr;
shared_reference(T* value) :m_ptr(value) { assert(value != nullptr); }
public:
shared_reference(const shared_reference&) = default;
shared_reference(shared_reference&&) = default;
~shared_reference() = default;
T* operator->() { return m_ptr.get(); }
const T* operator->() const { return m_ptr.get(); }
T& operator*() { return *m_ptr.get(); }
const T& operator*() const { return *m_ptr.get(); }
template <typename XT, typename...XTypes>
friend shared_reference<XT> make_shared_reference(XTypes&&...args);
};
template <typename T, typename...Types>
shared_reference<T> make_shared_reference(Types&&...args)
{
return shared_reference<T>(new T(std::forward<Types>(args)...));
}
Please note that operator= is missing yet. You should definitely add it.
You can use it like this:
#include <iostream>
using std::cout;
using std::endl;
struct test
{
int m_x;
test(int x) :m_x(x) { cout << "test("<<m_x<<")" << endl; }
test(const test& t) :m_x(t.m_x) { cout << "test(const test& " << m_x << ")" << endl; }
test(test&& t) :m_x(std::move(t.m_x)) { cout << "test(test&& " << m_x << ")" << endl; }
test& operator=(int x) { m_x = x; cout << "test::operator=(" << m_x << ")" << endl; return *this;}
test& operator=(const test& t) { m_x = t.m_x; cout << "test::operator=(const test& " << m_x << ")" << endl; return *this;}
test& operator=(test&& t) { m_x = std::move(t.m_x); cout << "test::operator=(test&& " << m_x << ")" << endl; return *this;}
~test() { cout << "~test(" << m_x << ")" << endl; }
};
#include <string>
int main() {
{
auto ref = make_shared_reference<test>(1);
auto ref2 = ref;
*ref2 = test(5);
}
{
test o(2);
auto ref = make_shared_reference<test>(std::move(o));
}
//Invalid case
//{
// test& a = *(test*)nullptr;
// auto ref = make_shared_reference<test>(a);
//}
}
Output:
test(1)
test(5)
test::operator=(test&& 5)
~test(5)
~test(5)
test(2)
test(test&& 2)
~test(2)
~test(2)
Example on Coliru
I hope I didn't forget anything that might result in undefined behaviour.
After taking a look at GSL's not_null class, which calls std::terminate() instead of abort();
Here is how I achieved it:
template <typename T>
class NonNull : public std::shared_ptr<T> {
typedef std::shared_ptr<T> super;
public:
inline NonNull()
: super(new T())
{
if ( ! super::get()) {
abort(); // Out of memory.
}
}
inline explicit NonNull(T *ptr)
: super(ptr)
{
if ( ! super::get()) {
abort(); // Input was null.
}
}
}
Basically, forces us to construct the class of T type.
Usage:
// Directly is a `std::shared_ptr` type:
NonNull<MyClass> myVariable;
// Unlike:
gsl::not_null<std::shared_ptr<MyClass > > myVariable;
Related
while experimenting with the answer from This post,
ended up with the following piece of code:
#include <iostream>
#include <typeinfo>
namespace Test
{
struct MyPtr
{
double operator, (int Input)
{
std::cout << "Operator, called" << std::endl;
return 1.0;
}
MyPtr operator* ()
{
std::cout << "operator* called" << std::endl;
return *this ;
}
MyPtr operator++ ()
{
std::cout << "operator++ called" << std::endl;
return *this;
}
MyPtr operator!= (const MyPtr& Other)
{
std::cout << "operator!= called" << std::endl;
return *this;
}
};
struct Foo
{
MyPtr Ptr;
};
MyPtr begin(Foo& t)
{
return t.Ptr;
}
MyPtr end(Foo& t)
{
return t.Ptr;
}
}
int main()
{
std::cout << typeid(decltype(++begin(std::declval<Test::Foo&>()),
*begin(std::declval<Test::Foo&>()),
std::true_type{})).name() <<std::endl;
}
which yields:
d
Here, d comes from the comma operator. However, as the last expression inside the decltype specifier is std::true_type{}, why does the decltype specifier resolves to the type returned by the comma operator instead of std::true type.
My Theory is that std::true_type can be implicitly cast into an int, which operator,() here takes as a parameter, hence the decltype expression is equivalent to:
std::cout << typeid(decltype(++begin(std::declval<Test::Foo&>()),
declval<double&>())).name() <<std::endl;
Can you confirm this is correct?
What i am planning on doing when i will have a better grasp of the compiler's behavior, i plan on replacing the contents of the decltype specifier with:
std::cout << typeid(decltype(void(++begin(std::declval<Test::Foo&>())),
void(*begin(std::declval<Test::Foo&>())),
std::true_type{})).name() <<std::endl;
which will prevent operator,() from matching, even if it is overridden. Can you also confirm this is correct?
I added a member to MyPtr to get more information. Then actually evaluating the expression tells you what happens:
#include <iostream>
#include <typeinfo>
struct MyPtr {
int value;
MyPtr(int x) : value(x) {}
double operator,(int Input) {
std::cout << "Operator, called value = " << value
<< " Input = " << Input << std::endl;
return 1.0;
}
MyPtr operator*() {
std::cout << "operator* called value = " << value << std::endl;
return *this;
}
MyPtr operator++() {
std::cout << "operator++ called value = " << value << std::endl;
return *this;
}
MyPtr operator!=(const MyPtr& Other) {
std::cout << "operator!= called" << std::endl;
return *this;
}
};
struct Foo { MyPtr Ptr; };
MyPtr begin(Foo& t) { return t.Ptr; }
MyPtr end(Foo& t) { return t.Ptr; }
int main() {
Foo f1{10};
Foo f2{20};
++begin(f1), *begin(f2), std::true_type{};
++begin(f1), *begin(f2), std::false_type{};
}
Output:
operator++ called value = 10
operator* called value = 20
Operator, called value = 20 Input = 1
operator++ called value = 10
operator* called value = 20
Operator, called value = 20 Input = 0
Your "Theory" is correct. Lets remove the ++ and * to make it simpler, then you can think of f1,f2,std::true_type{} as f1.operator,( f2.operator,(std::true_type{}). std::true_type has operator bool and bool can be implcicitly converted to int. To illustrate that I also added the example with false_type in the code.
The operator bool can be found here as operator value_type, because std::true_type is just an alias for std::integral_constant<bool,true>.
which will prevent operator,() from matching, even if it is overridden. Can you also confirm this is correct?
Yes. It is not possible to implement an comma operator overload for void.
I have a method that modifies objects passed by reference:
class MyClass;
MyClass& modify (MyClass& x) { ...; return x; }
What's the right way to extend modify to unnamed objects avoiding extra copies, so that the following code is valid?
MyClass createMyClass () { ... }
MyClass x = modify(createMyClass());
// instead of:
MyClass x = createMyClass();
modify(x);
PS: MyClass implements efficient moving.
It seems this code works with perfect forwarding, but not sure if you like it or not:
#include <memory>
#include <iostream>
struct T {
T() {std::cout << this << " ctor\n";}
~T() {std::cout << this << " dtor\n";}
T(const T& t) {std::cout << this << " cc\n"; i = t.i;}
T(T&& t) {std::cout << this << " mc\n"; i = t.i;}
T& operator=(const T& t) {std::cout << this << " ca\n"; i = t.i; return *this;}
T& operator=(T&& t) {std::cout << this << " ma\n"; i = t.i; return *this;}
int i = 0;
};
//T& modify (T& t) {t.i++; return t; }
template<typename X>
X modify (X&& t) { t.i++; return t; }
T create_T () { return T{}; }
int main() {
T t1 = modify(create_T());
std::cout << t1.i << "\n----------\n";
// instead of:
T t2 = create_T();
modify(t2);
std::cout << t2.i << "\n";
return 0;
}
And output will be like this:
0x7fff616d0fe0 ctor
0x7fff616d0fe8 mc
0x7fff616d0fe0 dtor
1
----------
0x7fff616d0fd8 ctor
1
0x7fff616d0fd8 dtor
0x7fff616d0fe8 dtor
You can also replace prefect forwarding with these 2 lines:
T& modify (T& t) { t.i++; return t; }
T modify (T&& t) { t.i++; return t; }
but not very interesting method.
Update:
For the reason that I don't know, following code does not generate similar output like perfect forwarding:
auto modify (auto&& t) { t.i++; return t; }
and output will be like this:
0x7ffcfa65c9a8 ctor
0x7ffcfa65c9b0 mc
0x7ffcfa65c9a8 dtor
1
----------
0x7ffcfa65c9a8 ctor
0x7ffcfa65c9b8 cc
0x7ffcfa65c9b8 dtor
1
0x7ffcfa65c9a8 dtor
0x7ffcfa65c9b0 dtor
Maybe the more experienced ones can tell the reasoning behind this difference.
I try to send to function a shared_ptr with polymorphic class.
My objective is to find a best way to send my shared_ptr
without increase ref_count.
EDIT: I don't search solution where my shared_ptr is replaced because I want to call shared_ptr.reset() for example.
Currently, void doGenericTemplate(std::shared_ptr<CLASS>& ptr) is what I want in result BUT I prefer a single function in program.
Do you have another solution ?
Moreover, I don't understand why the function void doGeneric(std::shared_ptr<Base>& ptr) doesn't compile (equivalent without shared_ptr work fine: please check doClassic in complete code).
Do you have an explain ?
Thanks you !
Partial code
#include <iostream>
#include <memory>
class Base
{
public:
Base() = default;
virtual ~Base() = default;
virtual void run() = 0;
};
class Derived1: public Base
{
public:
Derived1() = default;
virtual ~Derived1() = default;
void run()
{
std::cout << " Derived1";
}
};
class Derived2: public Base
{
public:
Derived2() = default;
virtual ~Derived2() = default;
void run()
{
std::cout << " Derived2";
}
};
// This function works but increase count
void doGenericCopy(std::shared_ptr<Base> ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
// This function works without increase count = OK !
void doSpecificD1(std::shared_ptr<Derived1>& ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
// Compilation error = FAILED !
void doGeneric(std::shared_ptr<Base>& ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
// Working fine for all Derivate = OK !
template<typename CLASS>
void doGenericTemplate(std::shared_ptr<CLASS>& ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
int main()
{
auto d1 = std::make_shared<Derived1>();
auto d2 = std::make_shared<Derived2>();
std::cout << "With copy: " << std::endl;
doGenericCopy(d1);
doGenericCopy(d2);
std::cout << "Specific: " << std::endl;
doSpecificD1(d1);
std::cout << "Template: " << std::endl;
doGenericTemplate(d1);
doGenericTemplate(d2);
// Compilation issue
//doGeneric(d1);
}
Complete code
https://ideone.com/ZL0v7z
Conclusion
Currently in c++, shared_ptr has not in language a specific tools to use polymorphism of class inside template.
The best way is to refactor my code and avoids to manage shared_ptr (ref_count, reset).
Thanks guys !
Do you have another solution ?
Pass object by reference or const reference instead of shared_ptr.
void doGeneric(Base& r)
{
r.run();
}
Firstly - this shows explicitly that you do not store or cache pointer somwhere. Secondly - you avoid ambiguities like the one you presented here.
Do you have an explain ?
Passing shared_ptr<Derived> to function causes implicit cast to shared_ptr<Base>. This new shared_ptr<Base> is temporary, so it can not be cast to shared_ptr<Base> &. This implicit cast would increase ref count even if you could pass it.
A shared_ptr<Base> and shared_ptr<Derived> are unrelated types, except you can implicitly create a shared_ptr<Base> from a shared_ptr<Derived>.
This creation adds a reference count.
If you really, really want to avoid that reference count...
template<class T>
struct shared_ptr_view {
template<class D>
shared_ptr_view( std::shared_ptr<D>& sptr ):
vtable( get_vtable<D>() ),
ptr( std::addressof(sptr) )
{}
shared_ptr_view( shared_ptr_view const& ) = default;
shared_ptr_view() = default;
shared_ptr_view& operator=( shared_ptr_view const& ) = delete;
T* get() const { if(vtable) return vtable->get(ptr); return nullptr; }
void clear() const { if(vtable) vtable->clear(ptr); }
std::shared_ptr<T> copy() const { if(vtable) return vtable->copy(ptr); return {} }
operator std::shared_ptr<T>() const { return copy(); }
T* operator->() const { return get(); }
T& operator*() const { return *get(); }
explicit operator bool() const { return get(); }
std::size_t use_count() const { if (vtable) return vtable->use_count(ptr); return 0; }
private:
struct vtable_t {
T*(*get)(void*) = 0;
std::shared_ptr<T>(*copy)(void*) = 0;
void(*clear)(void*) = 0;
std::size_t(*use_count)(void*) = 0;
};
vtable_t const* vtable = 0;
void* ptr = 0;
template<class D>
static vtable_t create_vtable() {
return {
[](void* ptr)->T*{ return static_cast<std::shared_ptr<D>*>(ptr)->get(); },
[](void* ptr)->std::shared_ptr<T>{ return *static_cast<std::shared_ptr<D>*>(ptr); },
[](void* ptr){ static_cast<std::shared_ptr<D>*>(ptr)->reset(); },
[](void* ptr){ return static_cast<std::shared_ptr<D>*>(ptr)->use_count(); }
};
}
template<class D>
static vtable_t const* get_vtable() {
static const auto vtable = create_vtable<D>();
return &vtable;
}
};
then
void doGeneric( shared_ptr_view<Base> ptr ) {
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
does not increase the reference count. I think it is raw insanity.
shared_ptr_view.clear() works, but shared_ptr_view.reset(T*) cannot: a shared_ptr_view<Derived> cannot be reset to point to a Base*.
Whilst trying to debug some code, I created a class to dump the values of a complicated hierarchy of objects to a text file so that I can compare a case where it works against a case where it doesn't. I implemented the class like this (reduced to a bare example):
#include <iostream>
class someOtherClass
{
public:
someOtherClass()
: a(0)
, b(1.0f)
, c(2.0)
{}
int a;
float b;
double c;
};
class logger
{
public:
// Specific case for handling a complex object
logger& operator << ( const someOtherClass& rObject )
{
std::cout << rObject.a << std::endl;
std::cout << rObject.b << std::endl;
std::cout << rObject.c << std::endl;
return *this;
}
// [other class specific implementations]
// Template for handling pointers which might be null
template< typename _T >
logger& operator << ( const _T* pBar )
{
if ( pBar )
{
std::cout << "Pointer handled:" << std::endl;
return *this << *pBar;
}
else
std::cout << "null" << std::endl;
return *this;
}
// Template for handling simple types.
template< typename _T >
logger& operator << ( const _T& rBar )
{
std::cout << "Reference: " << rBar << std::endl;
return *this;
}
};
int main(int argc, char* argv[])
{
logger l;
someOtherClass soc;
someOtherClass* pSoc = &soc;
l << soc;
l << pSoc;
pSoc = nullptr;
l << pSoc;
return 0;
}
I was expecting to get the following output:
0
1
2
Pointer handled:
0
1
2
null
But what I actually get is:
0
1
2
Reference: 010AF7E4
Reference: 00000000
The automatic type deduction appears to be picking the reference implementation and setting the type to someOtherClass* rather than picking the pointer implementation. I'm using Visual Studio 2012.
In logger& operator << ( const _T& rBar ) type T can be a pointer type, so in order to work properly this template needs some restriction:
template< typename _T , typename = typename ::std::enable_if_t<!std::is_pointer<_T>::value> >
logger& operator << ( const _T& rBar )
{
std::cout << "Reference: " << rBar << std::endl;
return *this;
}
Online compiler
This is required because when templates are instantiated the const _T & pBar with _T = someOtherClass * variant will be proffered as conversion sequence required in this case will only include a reference binding which is considered an identity conversion while const _T* pBar variant with _T = someOtherClass will involve a copy-initialization.
Here are a few modifications and annotations which may help as this logging class grows and becomes more mature.
I have attempted to:
a) solve the initial problem of incorrect type deduction.
b) decouple the logger from the things being logged (otherwise your logger has to know about the entire application and all libraries).
c) provide a mechanism for easily allowing logging of any type, even if provided by a third-party library.
#include <iostream>
// I've put the logger and its helpers into a namespace. This will keep code tidy and help with
// ADL.
namespace logging
{
// define a general function which writes a value to a stream in "log format".
// you can specialise this for specific types in std:: if you wish here
template<class T>
void to_log(std::ostream& os, T const& value)
{
os << value;
}
// define a general function objects for writing a log-representation of tyoe T.
// There are 2 ways to customise this.
// a) provide a free function called to_log in the same namespace as your classes (preferred)
// b) specialise this class.
template<class T>
struct log_operation
{
void operator()(std::ostream& os, T const& value) const
{
to_log(os, value);
}
};
// specialise for any pointer
template<class T>
struct log_operation<T*>
{
void operator()(std::ostream& os, T* ptr) const
{
if (!ptr)
os << "null";
else
{
os << "->";
auto op = log_operation<std::decay_t<T>>();
op(os, *ptr);
}
}
};
// the logger is now written in terms of log_operation()
// it knows nothing of your application's types
class logger
{
public:
// Template for handling any type.
// not that this will also catch pointers.
// we will disambiguate in the log_operation
template< typename T >
logger& operator << ( const T& rBar )
{
auto op = log_operation<std::decay_t<T>>();
op(std::cout, rBar);
std::cout << std::endl;
return *this;
}
};
}
class someOtherClass
{
public:
someOtherClass()
: a(0)
, b(1.0f)
, c(2.0)
{}
int a;
float b;
double c;
};
// someOtherClass's maintainer provides a to_log function
void to_log(std::ostream& os, someOtherClass const& c)
{
os << "someOtherClass { " << c.a << ", " << c.b << ", " << c.c << " }";
}
namespace third_party
{
// the is in a 3rd party library. There is no to_log function and we can't write one which will be found with
// ADL...
struct classWhichKnowsNothingOfLogs {};
}
/// ..so we'll specialise in the logging namespace
namespace logging
{
template<>
struct log_operation<::third_party::classWhichKnowsNothingOfLogs>
{
void operator()(std::ostream& os, ::third_party::classWhichKnowsNothingOfLogs const& value) const
{
os << "classWhichKnowsNothingOfLogs {}";
}
};
}
int main(int argc, char* argv[])
{
logging::logger l;
someOtherClass soc;
someOtherClass* pSoc = &soc;
l << soc;
l << pSoc;
pSoc = nullptr;
l << pSoc;
l << third_party::classWhichKnowsNothingOfLogs();
return 0;
}
expected output:
someOtherClass { 0, 1, 2 }
->someOtherClass { 0, 1, 2 }
null
classWhichKnowsNothingOfLogs {}
I'm trying to fix a double free or corruption in this class:
struct Holder
{
template <typename T>
Holder(const T& v)
{
_v = new T{};
memcpy(_v, &v, sizeof(T));
_deleter = [this]{
if (_v != nullptr)
{
delete reinterpret_cast<T*>(_v);
_v = nullptr;
}
};
}
template <typename T>
T get()
{
T t;
memcpy(&t, _v, sizeof(T));
return t;
}
~Holder()
{
std::cout << "~Holder() " << std::endl;
_deleter();
}
private:
void* _v;
std::function<void()> _deleter;
};
The goal of this class is to Hold a value of a particular type, like boost::any. So I'm trying to understand the mechanism to safely deallocate all memory.
Probably this line of code:
delete reinterpret_cast<T*>(_v);
doesn't do what I expect ...
**** After Suggestions ****
I've rewrite the code using comment suggestions and adding a move constructor
struct Holder
{
template <typename T>
Holder(const T& v)
{
std::cerr << "create " << N << std::endl;
_v = new T(v);
_deleter = [this]{
if (_v != nullptr)
{
std::cerr << "deleter " << N << std::endl;
delete reinterpret_cast<T*>(_v);
_v = nullptr;
}
};
}
Holder(Holder&& rs)
{
_v = rs._v;
_deleter = std::move(rs._deleter);
rs._deleter = []{}; //usefull to avoid a bad function call
}
template <typename T>
T get() const
{
return *reinterpret_cast<T*>(_v);
}
~Holder()
{
//std::cout << "~Holder() " << N << std::endl;
_deleter();
}
private:
void* _v;
std::function<void()> _deleter;
};
Now seems work but I have to manage others corner case :)
Probably the best solution is to use boost::any:
struct Holder
{
template <typename T>
Holder(const T& v)
{
_v = v;
}
template <typename T>
T get()
{
return boost::any_cast<T>(_v);
}
private:
boost::any _v;
};
But I'am trying to understand how it coudl works without it.
This is my last version:
struct Holder
{
template <typename T>
Holder(const T& v)
{
std::cerr << "create " << N << std::endl;
_v = new T(v);
_deleter = [](void* ptr){
if (ptr != nullptr)
{
std::cerr << "deleter " << std::endl;
delete reinterpret_cast<T*>(ptr);
}
};
_builder = [](void* &dest, void* src){
dest = new T(*reinterpret_cast<T*>(src));
};
}
Holder(const Holder& rs)
{
std::cerr << "copy constr" << std::endl;
if (this != &rs)
{
rs._builder(_v, rs._v);
_deleter = rs._deleter;
_builder = rs._builder;
}
}
Holder(Holder&& rs)
{
std::cerr << "move constr" << std::endl;
if (this != &rs)
{
_v = rs._v;
_deleter = std::move(rs._deleter);
_builder = std::move(rs._builder);
rs._deleter = [](void*){};
}
}
Holder& operator=(const Holder& rs)
{
std::cerr << "copy operator" << std::endl;
if (this != &rs)
{
rs._builder(_v, rs._v);
_deleter = rs._deleter;
_builder = rs._builder;
}
return *this;
}
Holder& operator=(Holder&& rs)
{
std::cerr << "move operator" << std::endl;
if (this != &rs)
{
_v = rs._v;
_deleter = std::move(rs._deleter);
_builder = std::move(rs._builder);
rs._deleter = [](void*){};
}
return *this;
}
template <typename T>
T get() const
{
return *reinterpret_cast<T*>(_v);
}
~Holder()
{
//std::cout << "~Holder() " << N << std::endl;
_deleter(_v);
}
private:
void* _v;
std::function<void(void* ptr)> _deleter;
std::function<void(void* &, void* src)> _builder;
};
Don't reimplement the horse.
using pvoid_holder = std::unique_ptr<void, std::function<void(void*)>>
template<class T>
pvoid_holder pvoid_it( T* t ) {
return { t, [](void* v){ if (v) delete static_cast<T*>(v); } };
}
Now store a pvoid_holder in your Holder class. It will handle memory lifetime for you.
You could use a naked pvoid_holder, but it might have a richer interface than you want (for example, it will allow the stored pointer to be changed without changing the deleter).
You can also replace std::function with void(*)(void*) for a marginal performance gain.
Here is a random idea. I still don't like it though. The whole idea behind this design is bad.
template <typename T>
struct Holder
{
public:
Holder(T const& v)
{
new (&m_v) T(v);
}
T const& get() const
{
return reinterpret_cast<T const&>(m_v);
}
T& get()
{
return reinterpret_cast<T&>(m_v);
}
~Holder()
{
std::cout << "~Holder() " << std::endl;
get().~T();
}
private:
char m_v[sizeof(T)];
};
This class doesn't do the same as yours anymore, ie it can't store arbitrary types in a std::vector<Holder> but only the same type (std::vector<Holder<Foo>>). A comment was too small to contain this code though and I wanted to show a better looking syntax for what you're playing with ;).
That being said, the only way you can do what you're trying to do is when you add a second layer for the reference counting. Ie, you replace your void* _v with something that resembles shared_ptr but which doesn't call delete when the count reaches zero but calls deleter (which therefore should be stored inside this new class). In fact your class looks mostly like this new class, except that you should make it non-copyable and provide reference counting (ie through boost::intrusive_ptr). Then Holder can be a wrapper around that that is copyable.
Probably this line of code: delete reinterpret_cast<T*>(_v); doesn't do what I expect ...
Not exactly. Your types are likely using a default copy ctor; this copies your data pointer _v, and your deleter. So when both objects destruct, both deleters trigger, causing the data to be deleted twice. (Side note--you shouldn't name variables starting with _; such identifiers are reserved for implementations).
Here's what it takes to do type erasure properly, assuming I've no bugs in it. A better way would be to stick to using boost::any.
#include <utility>
struct EmptyType {}; // Thrown if unexpectedly empty
struct InvalidType {}; // Thrown if Holder(T) but get<U>.
struct Holder
{
Holder()
: data_()
, deleter_(e_deleter)
, copier_(e_copier)
, typetag_()
{
}
template<typename T>
Holder(const T& t)
: data_(erase_cast(new T))
, deleter_(deleter<T>)
// Need to explicitly carry T's copy behavior
// because Holder's default copy ctor isn't going to
, copier_(copier<T>)
// You need some way to protect against getting
// an Orange out of a Holder that holds an Apple.
, typetag_(id<T>())
{
}
Holder(const Holder& rhs)
: data_(rhs.copy())
, deleter_(rhs.deleter_)
, copier_(rhs.copier_)
, typetag_(rhs.typetag_)
{
}
template<typename T>
T get()
{
if (!data_) throw EmptyType();
T rv(fetch<T>());
return rv;
}
Holder(Holder&& rhs)
: data_()
, copier_(rhs.copier_)
, deleter_(rhs.deleter_)
, typetag_(rhs.typetag_)
{
std::swap(data_, rhs.data_);
}
~Holder()
{
destroy();
}
private:
// Reinterpret_cast wrappers labeled semantically
template<typename T>
static void* erase_cast(T* t) { return reinterpret_cast<void*>(t); }
template<typename T>
static T* unerase_cast(void* t) { return reinterpret_cast<T*>(t); }
// Return a data copy
void* copy() const { return copier_(data_); }
// Return const reference to data
template<typename T>
const T& fetch() {
if (typetag_!=id<T>()) throw InvalidType();
return *unerase_cast<T>(data_);
}
// Destroy data
void destroy() { deleter_(data_); data_=0; }
// ==== Type erased copy semantics ===
void*(*copier_)(void*);
template<typename T>
static void* copier(void* v) {
return erase_cast<T>(new T(*unerase_cast<T>(v)));
}
static void* e_copier(void*) { return 0; }
// ==== Type erased delete semantics ===
void(*deleter_)(void*);
template<typename T>
static void deleter(void* v) {
delete unerase_cast<T>(v);
}
static void e_deleter(void*) {}
// ==== Type protection using tagging (could also use typeid)
static int makenewid() { static int i=0; return i++;}
template<typename T>
static int id() { static int i=makenewid(); return i; }
// Type erased data
void* data_;
// Type erased tag
int typetag_;
};
...and here is some test/demo code:
#include <iostream>
#include <vector>
#define FAIL() std::cout << "Fail" << std::endl; return 1
int foos=0;
struct Foo { Foo(){++foos;} Foo(const Foo&){++foos;} ~Foo(){--foos;} };
int bars=0;
struct Bar { Bar(){++bars;} Bar(const Bar&){++bars;} ~Bar(){--bars;} };
int main() {
{
std::vector<Holder> v;
Foo fx,fy,fz; Bar ba,bb;
v.push_back(fx); v.push_back(fy); v.push_back(fz);
v.push_back(ba); v.push_back(ba); v.push_back(bb);
v.push_back(Holder());
try {
Foo y = v[2].get<Foo>();
}
catch (EmptyType&) { FAIL(); }
catch (InvalidType&) { FAIL(); }
try {
Foo y = v[4].get<Foo>();
FAIL();
}
catch (EmptyType&) { FAIL(); }
catch (InvalidType&) { }
try {
Foo y = v[6].get<Foo>();
FAIL();
}
catch (EmptyType&) { }
catch (InvalidType&) { FAIL(); }
}
if (foos||bars) { FAIL(); }
std::cout << "Pass" << std::endl;
}
Test results:
$ ./a.exe
Pass