CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

  1. #1
    Join Date
    Mar 2006

    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:

    #include <memory>
    #include <vector>
    struct MyObject
        int a, b, c;
    struct MyGenerator
    // 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
    #include <iostream>
    int main(int, char **)
        MyGenerator x;
        int i = (*x.GetData())[0]->a;
    //    (*x.GetData())[0]->a = 5; // No! Should not be allowed!
        std::cout << "Done" << std::endl;
    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).

    Thank you,
    Last edited by GeoRanger; November 18th, 2013 at 01:44 PM. Reason: Forgot to add const to the template argument in shared_ptr

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.