C++-面试题:深度拷贝与构造函数中的异常

2014-11-24 11:23:55 · 作者: · 浏览: 1

昨天的一道面试题,分享下:

实现一个拷贝构造函数:

classFoo {

public:
Foo(A* a, B* b);

~Foo() {
delete a;

delete b;

}

// Implement copy constructor.

// Types A and B are Copy Constructible.

private:

A* a;

B* b;

};

答案:

Foo::Foo(const Foo& other)
{

this->a = new A(*other.a);

this->b = new B(*other.b);

}

备注:这道题主要考深度拷贝.

如果B会抛出异常,该如何处理?

答案:

Foo::Foo(const Foo& other)
{

this->a = new A(*other.a);

try{

this->b =new B(*other.b);

catch(…)

{

delete this->a;

this->a=nullptr;

}

}

如果不处理这个异常,会出现什么情况?如果是指针呢?

答案:内存泄露,如果是智能指针则不会出现内存泄露;

备注:这道题主要考如下知识点儿:

Objects Are Automatically Destroyed during StackUnwinding

When a block is exited during stack unwinding, the compilerguarantees that objects created in that block are properly destroyed.

If an exception occurs in a constructor, then the object underconstruction might be only partially constructed. Even if the object is onlypartially constructed, we are guaranteed that the constructed members will be properly destroyed.

由于智能指针有自己的析构函数,所以可以自动释放;但是使用new定义的指针就不行了,所以要内存泄露。