您可以编写一个完全有效的复制构造函数,并且仍然能够传递一个为 NULL 的引用。您可以测试 NULL,但前提是您不使用构造函数初始化列表。
例子:
MyClass::MyClass( MyClass const& MyClassCopy )
: somevar( MyClassCopy.somevar ) // <- the init list goes here.
{
// If MyClassCopy is NULL, the initialization above is doomed!
// However we can check for NULL in the constructor body but
// the initialization list must be removed ...
if (&MyClassCopy == NULL ) throw( std::runtime_error("NULL pointer!"));
somevar = MyClassCopy.somevar;
}
// I'll now do some very dangerous programming to
// demonstrate one way that a NULL can get through ...
MyClass* P = NULL;
MyClass A( *P ); // Bang, you're dead!
据我所知,没有办法从初始化列表中检查 NULL,所以如果你认为你最终可能会遇到 NULL 通过的情况,你必须在构造函数主体中测试它并执行从那里初始化。
不要忘记 ::operator=() 函数有一些注意事项......