Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast boost::shared_array<char> to boost::shared_array<const char>

How can I cast a boost::shared_array<char> to boost::shared_array<const char>?

like image 817
Joakim Karlsson Avatar asked Dec 04 '09 12:12

Joakim Karlsson


2 Answers

Since shared_array has no add_ref method you could emulate it as follows:

struct MagicDeleter {
  MagicDeleter( boost::shared_array<char> ptr ) : ptr(ptr) {};
  template<typename T> void operator()(T*) {} 
protected:
  boost::shared_array<char> ptr;
};

...

boost::shared_array<char> orig_ptr( some_val );
boost::shared_array<const char> new_ptr( orig_ptr.get(), MagicDeleter(orig_ptr) );
like image 199
Kirill V. Lyadvinsky Avatar answered Sep 28 '22 08:09

Kirill V. Lyadvinsky


The other answers are correct, you can't and you shouldn't.

Besides, are you sure you want a boost::shared_array<const char> and not a const boost::shared_array<char>?

Practically, this works:

boost::shared_array<char> acz;
boost::shared_array<const char>& acz2 = reinterpret_cast< boost::shared_array<const char>& >(acz);

BUT it is not a good idea and only works if boost::shared_array and boost::shared_array have the same implementation. Templates can be partially specialized:

template<class T>
struct TwoImplementations {
    int m_nIntMember;
};

template<>
struct TwoImplementations< const T > {
    double m_fDoubleMember;
};

Doing a reinterpret cast between TwoImplementations<int> and TwoImplementations<const int> is just wrong.

like image 23
Sebastian Avatar answered Sep 28 '22 08:09

Sebastian