设为首页 加入收藏

TOP

C++深度拷贝与构造函数的异常
2014-04-06 17:35:58 来源: 作者: 【 】 浏览:129
Tags:深度 拷贝 构造 函数 异常

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

  实现一个拷贝构造函数:

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇关于构造函数c++ 下一篇C++指针、引用知多少

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)