SaferCPlusPlus icon indicating copy to clipboard operation
SaferCPlusPlus copied to clipboard

Unsafety of the `this` pointer?

Open fehmud opened this issue 7 years ago • 1 comments

I cannot understand what is unsafe in the access of the this pointer provided here. I don't see any deallocation: iter is an automatic variable. Could you elaborate, please? Thanks.

fehmud avatar May 20 '18 03:05 fehmud

Sure. Let me add some code and comments to the example that might make thing clearer:

    #include <iostream>
    #include "msescope.h"
    #include "msemstdvector.h"
    
    class CI {
    public:
        ~CI {
            std::cout << "CI destructor called \n";
        }
    
        template<class safe_vector_pointer_type>
        void foo1(safe_vector_pointer_type vec_ptr) {
            std::cout << "foo1() called \n";
    
            /* The `this` pointer is valid here. */
            this->m_i += 1;
            assert(this == std::addressof(vec_ptr->front())); // just for this example
    
            vec_ptr->clear();
            vec_ptr->shrink_to_fit();
    
            /* In this example, the `this` pointer is no longer valid here. The object it pointed to was just 
            destroyed by the `vec_ptr->clear()` operation. */
    
            std::cout << "but we're not finished using the CI object yet \n";
    
            /* These next two lines are equivalent and technically unsafe. */
            m_i += 1;
            this->m_i += 1;
        }
    
        int m_i = 0;
    };
    
    void main() {
        mse::TXScopeObj<mse::mstd::vector<CI>> vec1;
        vec1.resize(1);
        auto iter = vec1.begin();
        iter->foo1(&vec1);
    }

I think I've got that right. I didn't test it. But does that help? It also might help to step through the code with your favorite interactive debugger.

duneroadrunner avatar May 21 '18 07:05 duneroadrunner