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.
1条答案
按热度按时间eyh26e7m1#
为了避免
NULL
指针的风险,根本不要传递指针,而是使用引用(没有'null'引用)。例如: