raii

Can you use a shared_ptr for RAII of C-style arrays?

微笑、不失礼 提交于 2019-11-30 00:02:42
I'm working on a section of code that has many possible failure points which cause it to exit the function early. The libraries I'm interacting with require that C-style arrays be passed to the functions. So, instead of calling delete on the arrays at every exit point, I'm doing this: void SomeFunction(int arrayLength) { shared_ptr<char> raiiArray(new char[arrayLength]); pArray = raiiArray.get(); if(SomeFunctionThatRequiresCArray(pArray) == FAILED) { return; } //etc. } I wanted to use unique_ptr , but my current compiler doesn't support it and the reference count overhead doesn't really matter

Making a HANDLE RAII-compliant using shared_ptr with a custom deleter

偶尔善良 提交于 2019-11-29 17:47:56
问题 I've recently posted a general question about RAII at SO. However, I still have some implementation issues with my HANDLE example. A HANDLE is typedeffed to void * in windows.h . Therefore, the correct shared_ptr definition needs to be std::tr1::shared_ptr<void> myHandle (INVALID_HANDLE_VALUE, CloseHandle); Example 1 CreateToolhelp32Snapshot : returns HANDLE and works. const std::tr1::shared_ptr<void> h (CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL), CloseHandle); As I use void in the

How does RAII work when a constructor throws an exception?

扶醉桌前 提交于 2019-11-29 16:39:36
问题 I am learning about the RAII idiom in C++, and how to use smart pointers. In my reading, I have come across two things that, to me, seem to contradict each other. Quoted from http://www.hackcraft.net/raii/: ...if a member object with RAII semantics has been created and an exception happens before the constructor has completed then its destructor will be called as part of the stack unwinding. Hence an object which controls multiple resources can guarnatee their cleanup even if it isn’t fully

Detecting when destructor running due to exception being thrown?

耗尽温柔 提交于 2019-11-29 16:32:56
问题 What is a good way in C++ to detect in a destructor that it is being run during unwind of the stack due to an exception being thrown as opposed to a normal exit of scope triggering the destructor? I'd like to know so that I can create a class that has some cleanup code that is always run on normal exit but skipped when an exception occurs. 回答1: std::uncaught_exception() (defined in <exception> ) will tell you in your destructor if it was called because of an exception: class A { public: ~A()

How should one log when an exception is triggered?

霸气de小男生 提交于 2019-11-29 13:45:08
In a program I recently wrote, I wanted to log when my "business logic" code triggered an exception in third-party or project APIs. ( To clarify, I want to log when use of an an API causes an exception. This can be many frames above the actual throw , and may be many frames below the actual catch ( where logging of the exception payload can occur. ) ) I did the following: void former_function() { /* some code here */ try { /* some specific code that I know may throw, and want to log about */ } catch( ... ) { log( "an exception occurred when doing something with some other data" ); throw; } /*

Typedef a shared_ptr type with a static custom deleter, similar to unique_ptr

北战南征 提交于 2019-11-29 11:37:53
I have read through many questions on SO on custom deleter for shared_ptr and unique_ptr , and the difference between the two. But, I still haven't found any clear answer to this question: How can one best go about creating a type that acts as a shared_ptr with a custom deleter, similar to how unique_ptr has the deleter as part of the type definition? For unique_ptr usage, I use a deleter class, that handles deletion of individual types (limiting it to just two types, for brevity): struct SDL_Deleter { void operator()( SDL_Surface* ptr ) { if (ptr) SDL_FreeSurface( ptr );} void operator()( SDL

What is standard defer/finalizer implementation in C++?

旧城冷巷雨未停 提交于 2019-11-29 09:36:56
问题 General idea of Golang-style defer is explained here and here. I wonder, does STL (of C++11, C++14, ...) or maybe Boost or maybe some other library contain implementation of such a class? So I could just use it without reimplementing it in every new project. 回答1: There is a proposal for std::unique_resource_t which will enable code like auto file=make_unique_resource(::fopen(filename.c_str(),"w"),&::fclose); for resources, and it defines a general scope_exit , which should be the same as

Where's the proper (resource handling) Rule of Zero? [closed]

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 09:29:25
Here's an article that talks about an idiom named Rule of Zero . Here's an excerpt: class module { public: explicit module(std::wstring const& name) : handle { ::LoadLibrary(name.c_str()), &::FreeLibrary } {} // other module related functions go here private: using module_handle = std::unique_ptr<void, decltype(&::FreeLibrary)>; module_handle handle; }; It reuses unique_ptr RAII features so you don't need to care about implementing a daunting and verbose Rule of Five wrapper. Presented this way (managing handle based resources with unique_ptr , that way), it looks as a hack for me, not a best

Do boost asio sockets have proper RAII cleanup

我与影子孤独终老i 提交于 2019-11-29 07:02:52
I tried looking through source but I cant navigate that much of a template code. Basically: this is what documentation says (for close() ): Remarks For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket. I can do that manually, but if possible it would be nice to rely on RAII. So if I have socket going out of scope do I need to call shutdown() and close() on it, or it will be done automatically? One can rely on the socket performing proper cleanup with RAII. When an IO object, such as socket, is destroyed, its destructor will

Pattern name for create in constructor, delete in destructor (C++)

醉酒当歌 提交于 2019-11-29 03:59:42
Traditionally, in C++, you would create any dependencies in the constructor and delete them in the destructor. class A { public: A() { m_b = new B(); } ~A() { delete m_b; } private: B* m_b; }; This technique/pattern of resource acquisition, does it have a common name? I'm quite sure I've read it somewhere but can't find it now. Edit: As many has pointed out, this class is incomplete and should really implement a copy constructor and assignment operator. Originally, I intentionally left it out since it wasn't relevant to the actual question: the name of the pattern. However, for completeness