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

后端 未结 1 1065
余生分开走
余生分开走 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 <memory> // for pointer_traits
    
    template <typename Pointer>
    class ConstPropagatePointer 
    {
    public:
        using element_type = typename std::pointer_traits<Pointer>::element_type;
        using pointer = typename std::pointer_traits<Pointer>::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<char*> str; 
        ConstPropagatedPointer<ComplexObj*> obj; 
        ConstPropagatedPointer<std::shared_ptr<ComplexObj>> obj2;
    };
    
    0 讨论(0)
提交回复
热议问题