灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:6559回复:0

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

楼主#
更多 发布于:2014-04-10 09:59
 昨天的一道面试题,分享下:
  实现一个拷贝构造函数:
  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定义的指针就不行了,所以要内存泄露。

喜欢0 评分0
游客

返回顶部