November 18th, 2013, 01:34 PM
is this cast to add const guaranteed to be OK?
I have a class in a speed critical program which contains some data to be shared with callers outside the class. The data is reasonably large and copying it should be avoided as much as possible. However, it is imperative that the callers not be allowed to modify the data. This example program highlights the problem:
My question is, is the cast I'm making in GetData() always going to be acceptable? (Does the C-Standard address this issue?) It seems like if either vector<> or shared_ptr<> ever had a template specialization for const template arguments it could cause this to fail (catastrophically).
int a, b, c;
// No good -- allows modification of vector content.
// std::shared_ptr<std::vector<MyObject *>> GetData(void) const
// return m_ptrvData;
std::shared_ptr<std::vector<MyObject const *> const> GetData(void) const
// return m_ptrvData; // C2664
return *reinterpret_cast<std::shared_ptr<std::vector<MyObject const *> const> const *>(&m_ptrvData);
std::shared_ptr<std::vector<MyObject *>> m_ptrvData; // The vector gets populated by other class members
int main(int, char **)
int i = (*x.GetData())->a;
// (*x.GetData())->a = 5; // No! Should not be allowed!
std::cout << "Done" << std::endl;
Last edited by GeoRanger; November 18th, 2013 at 01:44 PM.
Reason: Forgot to add const to the template argument in shared_ptr
Click Here to Expand Forum to Full Width