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

本文详细介绍了如何实现C++类的拷贝构造函数,包括深度拷贝的概念,并提供了处理B类型可能抛出异常的解决方案。同时,文章探讨了异常处理在构造函数中的应用及其后果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

实现一个拷贝构造函数:

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定义的指针就不行了,所以要内存泄露。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值