本文介绍了从复制构造函数中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们说从

构造函数抛出异常是一种糟糕的技术;并且解决方案是创建一个函数

_create_来初始化一个对象。


复制构造函数怎么样?我们如何避免抛出异常?如果

我们已经有一个abject女巫被初始化机智_create_我们将

被迫在复制构造函数中调用create并从

中抛出异常它。


祝你有愉快的一天,

Mihai。

People say that is a bad technique to throw exception from
constructors; and that the solution would be to create a function
_create_ to initialize an object.

What about copy constructors? How can we avoid throwing exceptions? If
we already have an abject witch was initialized wit _create_ we will be
forced to call create in copy constructor and to throw exceptions from
it.

Have a nice day,
Mihai.

推荐答案




我不相信消息灵通的人说施工人员不应该扔。

他们确实说*破坏者*不应该扔掉。


构造函数抛出异常可能会导致问题,因为它b / b $ b意味着没有调用析构函数,这可能意味着必要

cleanup doesn'不会发生。


处理这个问题的标准方法是在A类中包装任何需要在其自己的类中清理的
(比方说,B,C和D类,然后制作那些类别(比如说,b,c和d)A成员的对象
。初始化

of b, c和d然后可以在A'的构造函数中出现(通过初始化

列表)。例如,如果d的初始化导致异常,则b和c

将完全构造(与A对象不同),因此将调用它们的

析构函数,即使A对象的构造函数不是。

这实现了必要的清理。


关于异常和错误处理的C ++ FAQ对此有一些有用的东西:



-

John Carson


I don''t believe that well-informed people say constructors shouldn''t throw.
They do say that *destructors* shouldn''t throw.

The throwing of an exception by a constructor can cause a problem because it
means that the destructor is not called, which may mean that necessary
cleanup doesn''t occur.

The standard way to handle this is to wrap anything in class A that needs to
be cleaned up in a class of its own (say, classes B, C and D) and then make
objects of those classes (say, b, c and d) members of A. The initialisation
of b, c and d can then occur in A''s constructor (via the initialisation
list). If, say, the initialisation of d causes an exception, then b and c
will have been fully constructed (unlike the A object) and hence their
destructors will be called, even though the A object''s constructor won''t be.
This achieves the necessary cleanup.

The C++ FAQ on Exceptions and Error Handling has some useful stuff on this:

http://www.parashift.com/c++-faq-lite/exceptions.html

--
John Carson



这篇关于从复制构造函数中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:59