Search code examples
c++pointersmanaged-c++

Assumptions when accessing private member pointer inside class


I have a class which contains a private pointer to a struct (This is managed C++ and the struct is native). The object this pointer points to is basically created in the constructor and lives until the containing class is disposed of. There is no code that reassigns the pointer to another object once it is assigned in the constructor of Foo and I don't envision there will be any in the future.

I am not interested in answers that pertain to using smart pointers, as I work with a lot of raw pointers in some legacy code. Porting everything over is another matter and something that is being planned.

My questions are:

  1. What can I assume about the pointer while working in the class in terms of validity?

  2. If I have several private functions that use the class...should I always check for a nullptr before dereferencing in those functions, or can I assume the pointer points to a valid object given the way the class is constructed (If this were native C++ I would just make the pointer an actual object to make this go away)?

  3. Any better ways of doing this that don't involve creating another managed wrapper for SomeStructType or smart pointers?

    public ref class Foo
    {        
        private:
    
        SomeStructType* pMyStruct;        
    
        void Initialize()
        {
            pMyStruct = new SomeStructType();
        }
    
        void DoSomethingElse1();  //Uses pMyStruct
        void DoSomethingElse2();  //Uses pMyStruct
    
        public:
    
        void DoSomething();  //Uses pMyStruct or calls private func that does
    
        Foo()
        {
            Initialize();
        }
    
        ~Foo()
        {
            delete pMyStruct;
        }
    }
    

Solution

  • No, you don't need to check it every time, since the contract (and rules of C++) implies that the object will always exist at any point you could attempt to access it in a valid way.

    If it can be reassigned, and you're in a multithreaded environment, you'd probably want to lock access to it. That would be the only issue I can think of.