失败的构造函数和失败的析构函数在C ++ [英] failed constructor and failed destructor in C++

查看:213
本文介绍了失败的构造函数和失败的析构函数在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题关于失败的构造函数和失败的析构函数在C ++。

I have one question about failed constructor and failed destructor in C++.

我注意到当构造函数失败时,会抛出异常。但是在析构函数中没有抛出异常。

I noticed that when the constructor failed, an exception will be thrown. But there is no exception thrown in destructor.

我的问题是

1)如果构造函数失败,会抛出什么异常? bad_alloc?或任何其他相关?在什么情况下,构造函数会失败?成功构建的部分怎么样?

1) If constructor failed, what exception will be thrown? bad_alloc? or anything else related? Under what situation, a constructor would fail? What about the successfully constructed part?

2)在什么情况下,析构函数会失败?如果没有抛出异常,析构函数会发生什么?编译器如何处理它?

2) Under what situation, a destructor would fail? If no exception is thrown, what would happen to the destructor? How does the compiler deal with it? What's the return value to the function it is called?

谢谢!

任何意见都非常感谢! / p>

Any comments are strongly appreciated!

推荐答案


  1. 如果构造函数失败,则只有在实现构造函数时才抛出异常它抛出异常。使用 new 分配内存可能会抛出一个 std :: bad_alloc 例外。)

  1. If a constructor fails, an exception is thrown only if the constructor is implemented so that it throws an exception. (You might need to differentiate between memory allocation and construction. Allocating memory using new might fail throwing a std::bad_alloc exception.)

没有一个构造函数通常失败的情况。它只有在写入时才会失败,从而可能会失败。如果是这样,它如何失败取决于它是如何写的。一般来说,析构函数应该写成不会失败,因为从析构函数中抛出异常是不安全的。 (这是因为在堆叠展开期间可能会调用它们。)

There is no case where a constructor, in general, fails. It fails only if it is written so that it might fail. If so, how it fails depends on how it is written. In general, destructors should be written so they don't fail, as it is not safe to throw exceptions from destructors. (That's because they might be called during stack unwinding.)

请注意,指运行时故障。所以编译器与它无关。此外,构造函数和析构函数都不返回任何东西。

Note that "failing" as used in your question generally refers to runtime failures. So the compiler has nothing to do with it. Also, neither constructors nor destructors return anything.

这篇关于失败的构造函数和失败的析构函数在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆