最后在 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/390615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finally in C++
提问by Tamara Wijsman
Is this a good way to implement a Finally-like behavior in standard C++? (Without special pointers)
这是在标准 C++ 中实现类似最终行为的好方法吗?(无特殊指示)
class Exception : public Exception
{ public: virtual bool isException() { return true; } };
class NoException : public Exception
{ public: bool isException() { return false; } };
Object *myObject = 0;
try
{
// OBJECT CREATION AND PROCESSING
try
{
myObject = new Object();
// Do something with myObject.
}
// EXCEPTION HANDLING
catch (Exception &e)
{
// When there is an excepion, handle or throw,
// else NoException will be thrown.
}
throw NoException();
}
// CLEAN UP
catch (Exception &e)
{
delete myObject;
if (e.isException()) throw e;
}
- No exception thrown by object -> NoException -> Object cleaned up
- Exception thrown by object -> Handled -> NoException -> Object cleaned up
- Exception thrown by object -> Thrown -> Exception -> Object cleaned up -> Thrown
- 对象没有抛出异常 -> NoException -> 对象已清理
- 对象抛出的异常 -> 已处理 -> NoException -> 对象已清理
- 对象抛出的异常 -> 抛出 -> 异常 -> 对象清理 -> 抛出
回答by David Norman
The standard answer is to use some variant of resource-allocation-is-initializationabbreviated RAII. Basically you construct a variable that has the same scope as the block that would be inside the block before the finally, then do the work in the finally block inside the objects destructor.
标准答案是使用缩写为 RAII的资源分配是初始化的一些变体。基本上,您构造一个变量,该变量与位于 finally 之前的块内的块具有相同的作用域,然后在对象析构函数内的 finally 块中进行工作。
try {
// Some work
}
finally {
// Cleanup code
}
becomes
变成
class Cleanup
{
public:
~Cleanup()
{
// Cleanup code
}
}
Cleanup cleanupObj;
// Some work.
This looks terribly inconvenient, but usually there's a pre-existing object that will do the clean up for you. In your case, it looks like you want to destruct the object in the finally block, which means a smart or unique pointer will do what you want:
这看起来非常不方便,但通常有一个预先存在的对象会为您进行清理。在您的情况下,您似乎想在 finally 块中销毁对象,这意味着智能或唯一指针将执行您想要的操作:
std::unique_ptr<Object> obj(new Object());
or modern C++
或现代 C++
auto obj = std::make_unique<Object>();
No matter which exceptions are thrown, the object will be destructed. Getting back to RAII, in this case the resource allocation is allocating the memory for the Object and constructing it and the initialization is the initialization of the unique_ptr.
无论抛出哪些异常,对象都会被销毁。回到 RAII,在这种情况下,资源分配是为 Object 分配内存并构造它,初始化是 unique_ptr 的初始化。
回答by Johannes Schaub - litb
No. The Standard way to build a finally like way is to separate the concerns (http://en.wikipedia.org/wiki/Separation_of_concerns) and make objects that are used within the try block automatically release resources in their destructor (called "Scope Bound Resource Management"). Since destructors run deterministically, unlike in Java, you can rely on them to clean up safely. This way the objects that aquired the resource will also clean up the resource.
不。构建 finally 类似方法的标准方法是分离关注点(http://en.wikipedia.org/wiki/Separation_of_concerns)并使在 try 块中使用的对象自动释放其析构函数中的资源(称为“范围绑定资源管理”)。由于析构函数确定性地运行,不像在 Java 中,您可以依靠它们来安全地清理。这样,获取资源的对象也将清理资源。
One way that is special is dynamic memory allocation. Since you are the one aquiring the resource, you have to clean up again. Here, smart pointers can be used.
一种特殊的方法是动态内存分配。由于您是获取资源的人,因此您必须再次清理。在这里,可以使用智能指针。
try {
// auto_ptr will release the memory safely upon an exception or normal
// flow out of the block. Notice we use the "const auto_ptr idiom".
// http://www.gotw.ca/publications/using_auto_ptr_effectively.htm
std::auto_ptr<A> const aptr(new A);
}
// catch...
回答by Steve Jessop
If for some strange reason you don't have access to the standard libraries, then it's very easy to implement as much as you need of a smart pointer type to handle the resource. It may look a little verbose, but it's less code than those nested try/catch blocks, and you only have to define this template once ever, instead of once per resource that needs management:
如果由于某些奇怪的原因您无法访问标准库,那么很容易实现您需要的智能指针类型来处理资源。它可能看起来有点冗长,但它的代码比那些嵌套的 try/catch 块要少,而且您只需定义一次此模板,而不是为每个需要管理的资源定义一次:
template<typename T>
struct MyDeletable {
explicit MyDeletable(T *ptr) : ptr_(ptr) { }
~MyDeleteable() { delete ptr_; }
private:
T *ptr_;
MyDeletable(const MyDeletable &);
MyDeletable &operator=(const MyDeletable &);
};
void myfunction() {
// it's generally recommended that these two be done on one line.
// But it's possible to overdo that, and accidentally write
// exception-unsafe code if there are multiple parameters involved.
// So by all means make it a one-liner, but never forget that there are
// two distinct steps, and the second one must be nothrow.
Object *myObject = new Object();
MyDeletable<Object> deleter(myObject);
// do something with my object
return;
}
Of course, if you do this and then use RAII in the rest of your code, you'll eventually end up needing all the features of the standard and boost smart pointer types. But this is a start, and does what I think you want.
当然,如果您这样做,然后在其余代码中使用 RAII,您最终将需要标准和 boost 智能指针类型的所有功能。但这是一个开始,并且会做我认为你想要的。
The try ... catch approach probably won't work well in the face of maintenance programming. The CLEAN UP block isn't guaranteed to be executed: for example if the "do something" code returns early, or somehow throws something which is not an Exception. On the other hand, the destructor of "deleter" in my code is guaranteed to be executed in both those cases (although not if the program terminates).
面对维护编程,try ... catch 方法可能不会很好地工作。CLEAN UP 块不能保证被执行:例如,如果“做某事”代码提前返回,或者以某种方式抛出一些不是异常的东西。另一方面,我的代码中“deleter”的析构函数保证在这两种情况下都会执行(尽管如果程序终止则不会)。
回答by Marc
My advice is: don't try to emulate the behaviour of a try-finally clause in C++. Just use RAII instead. You'll live happier.
我的建议是:不要试图模仿 C++ 中 try-finally 子句的行为。只需使用 RAII。你会活得更开心。
回答by Drew Dormann
To directly answer your question, no.
要直接回答您的问题,没有。
It's a clever way to implement that functionality, but it is not reliable. One way that will fail you is if your "do something" code throws an exception that is not derived from Exception
. In that case, you will never delete myObject
.
这是实现该功能的巧妙方法,但并不可靠。会让你失败的一种方式是,如果你的“做某事”代码抛出一个不是从Exception
. 在那种情况下,你永远不会delete myObject
。
There's a more important issue at hand here, and that's the methodologies adopted by programmers of any particular language. The reason you're hearing about RAIIis because programmers with much more experience than you or I have found that in the domain of C++ programming, that methodology is reliable. You can rely on other programmers using it and other programmers will want to rely on you using it.
这里有一个更重要的问题,那就是任何特定语言的程序员采用的方法。您听说RAII的原因是因为比您或我拥有更多经验的程序员发现,在 C++ 编程领域中,这种方法是可靠的。你可以依赖其他程序员使用它,其他程序员会希望你使用它。
回答by Jason S
Assuming you are looking to delete the pointer myObject and avoid memory leaks, your code can still fail to do this if there is a "return" statement in the code where you say // Do something with myObject.
(I am assuming real code would be here)
假设您要删除指针 myObject 并避免内存泄漏,如果您说的代码中有“return”语句,您的代码仍然无法执行此操作// Do something with myObject.
(我假设真正的代码将在此处)
RAII techniques have the relevant action that is equivalent to a "finally" block, in a particular object's destructor:
RAII 技术在特定对象的析构函数中具有相当于“finally”块的相关操作:
class ResourceNeedingCleanup
{
private:
void cleanup(); // action to run at end
public:
ResourceNeedingCleanup( /*args here*/) {}
~ResourceNeedingCleanup() { cleanup(); }
void MethodThatMightThrowException();
};
typedef boost::shared_ptr<ResourceNeedingCleanup> ResourceNeedingCleanupPtr;
// ref-counted smart pointer
class SomeObjectThatMightKeepReferencesToResources
{
ResourceNeedingCleanupPtr pR;
void maybeSaveACopy(ResourceNeedingCleanupPtr& p)
{
if ( /* some condition is met */ )
pR = p;
}
};
// somewhere else in the code:
void MyFunction(SomeObjectThatMightKeepReferencesToResources& O)
{
ResourceNeedingCleanup R1( /*parameters*/) ;
shared_ptr<ResourceNeedingCleanup> pR2 =
new ResourceNeedingCleanup( /*parameters*/ );
try
{
R1.MethodThatMightThrowException();
pR2->MethodThatMightThrowException();
O->maybeSaveACopy(pR2);
}
catch ( /* something */ )
{
/* something */
}
// when we exit this block, R1 goes out of scope and executes its destructor
// which calls cleanup() whether or not an exception is thrown.
// pR2 goes out of scope. This is a shared reference-counted pointer.
// If O does not save a copy of pR2, then pR2 will be deleted automatically
// at this point. Otherwise, pR2 will be deleted automatically whenever
// O's destructor is called or O releases its ownership of pR2 and the
// reference count goes to zero.
}
I think I have the semantics correct; I haven't used shared_ptr much myself, but I prefer it to auto_ptr<> -- a pointer to an object can only be "owned" by one auto_ptr<>. I've used COM's CComPtrand a variant of it that I've written myself for "regular" (non-COM) objects that is similar to shared_ptr<> but has Attach() and Detach() for transfer of pointers from one smart pointer to another.
我认为我的语义是正确的;我自己并没有经常使用 shared_ptr,但我更喜欢它而不是 auto_ptr<>——指向对象的指针只能由一个 auto_ptr<>“拥有”。我使用了 COM 的CComPtr和它的一个变体,我为“常规”(非 COM)对象编写了它,类似于 shared_ptr<> 但有 Attach() 和 Detach() 用于从一个智能传输指针指向另一个。