is this cast to add const guaranteed to be OK?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Thread: is this cast to add const guaranteed to be OK?

Threaded View

  1. #1
    Join Date
    Mar 2006
    Posts
    137

    is this cast to add const guaranteed to be OK?

    Hi,

    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:

    Code:
    #include <memory>
    #include <vector>
    
    struct MyObject
    {
        int a, b, c;
    };
    
    struct MyGenerator
    {
    public:
    // 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);
        }
    private:
        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,
    GeoRanger
    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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center