c++ 如何保护类成员变量指针?[duplicate]

juzqafwq  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(168)

This question already has answers here:

Ensuring compilation error while passing null pointer to a function (3 answers)
Closed yesterday.
I am looking for a way to protect a class from receiving a NULL pointer at compiler time.

class B
{
   // gives some API

}

class A
{

    private:
        B* ptrB_;
    
    public:
        A(B* ptrB) 
        {
            // How can I prevent the class to be created with a null pointer?
            ptrB_ = ptrB;
        }

        // multiple member function using: ptrB_ 
        void A::Func1(void)
        {
            if(!ptrB_ )
                rerturn; // I don't want to add it in every function.

            ...

            return;
        }

}

int main()
{
   B tempB = NULL;
   A tempA(&tempB);
}

How can I force user to always pass a pointer (not NULL) to A constructor?
Was looking at constexpr , but this forces to use static , and that's something I am trying to avoid.

eyh26e7m

eyh26e7m1#

为了避免NULL指针的风险,根本不要传递指针,而是使用引用(没有'null'引用)。
例如:

A(B* ptrB) { ptrB_ =  ptrB; } //instead of passing the address of an object
A(B& ptrB) { ptrB_ = &ptrB; } //take and store the address of the reference

相关问题