C++ Preventing const methods from changing data through a member pointer or reference

后端 未结 1 1067
余生分开走
余生分开走 2021-02-14 00:17

Say I have a simple class like this

class Foo
{
public:
    void foo()const
    {
        str[5] = \'x\';
        obj->changeTheWorld();
        x = 4;
               


        
1条回答
  •  无人共我
    2021-02-14 00:52

    Well, neither std::reference_wrapper nor std::shared_ptr do not provide const propagation, so they are not more "const-strict" than regular pointer.

    I'd recommend to make your own const propagation class (I am not sure - maybe something similar is already provided by boost - please let me know in comments)

    My proposition is this class:

    #include  // for pointer_traits
    
    template 
    class ConstPropagatePointer 
    {
    public:
        using element_type = typename std::pointer_traits::element_type;
        using pointer = typename std::pointer_traits::pointer;
        using const_pointer = element_type const * const;
        using reference = element_type&;
        using const_reference = element_type const&;
    
        ConstPropagatePointer(Pointer ptr) : ptr(ptr) {}
        pointer operator -> ()
        {
            return &(*ptr);
        }
        const_pointer operator -> () const
        {
            return &(*ptr);
        }
        reference operator * ()
        {
            return *ptr;
        }
        const_reference operator * () const 
        {
            return *ptr;
        }
    private:
        Pointer ptr;
    };
    

    So that will work for you:

    class Foo
    {
    public:
    private:
        ConstPropagatedPointer str; 
        ConstPropagatedPointer obj; 
        ConstPropagatedPointer> obj2;
    };
    

    0 讨论(0)
提交回复
热议问题