problem about raii-Collection of common programming errors


  • thehouse
    c++ coding-style shared-ptr raii idiomatic
    Is it acceptable C++ style to let create classes that wrap shared handles be copyable?Very frequently I find myself writing classes that hide the details of some gnarly C library or OS resource by holding a shared_ptr to it behind the class interface. E.g.class window { public:window() : m_handle(OsCreateWindow(), OsDestroyWindow) {}void make_it_dance();void paint_it_red(); private:shared_ptr<OS_WINDOW_HANDLE> m_handle; }Because the classes are copyable and shared_ptr does the hard work,

  • Billy ONeal
    c++ windows raii
    I’m writing a class library that provides convenient object-oriented frontends to the C API that is the Windows Registry. I’m curious, however, what the best course of action is for handling HREGs, for instances where my key class is copied.I can eitherAllocate a heap integer and use it as a reference count. Call RegCloseKey() on the handle and deallocate the integer when the refrence count equals zero. Use the builtin functionality of handles, and rather than maintaining a reference count, call

  • theDmi
    c++ stack raii new-operator
    I read in this blog, that making the new operator private is a good approach to enforce instantiation on the stack.I am implementing a class that employs the RAII idiom. This class should obviously only be instantiated on the stack, so I am looking for a way to enforce that.My question is, does this have any side effects that are not straight-forward to see? Is it a good approach to enforce instantiation on the stack? Are there any portability issues?Thanks for your help!EDITMy RAII class just

  • jrk
    c exceptions api-design c++11 raii
    I have an API written in C, which produces a result by returning a pointer to allocated memory. For using it with C++ (C++11) I’ve wrapped the function calls in objects, which keep the result in a std::shared_ptr. So far so good.However, the C library features two functions for every operation. One produces possibly an error, the other never. Let’s call them some_pod * do_it_with_error(Parameter …, Error **) and some_pod * do_it_without_error(Parameter …) I can pass in the address of an Err

  • Wesley Murch
    php raii
    I’m coming from C++ where I regularly employ RAII.PHP, as far as I know, uses automatic memory management, so is it still applicable/good practice to use RAII through constructors/destructors with PHP?

  • Jörgen Sigvardsson
    objective-c raii exception-safety
    I find myself writing code like this to achieve exception safe code:Container* container = [Container new]; @try {while(someCondition) {ElementType* value = [someObject createObjectFromStorage];[container add:value]; // container retains object[value release];}[_container release];_container = [container retain]; } @finally {[container release]; }Is there some other, and more succinct pattern to follow in Objective-C?

  • darvids0n
    garbage-collection raii
    This may be an eminently closeable question, but I’m the type that sees what sticks to the wall. For all of the benefits of memory and lifetime management afforded by a garbage collected runtime, have there been any notable cases of program indeterminacy caused by race conditions between an application and its garbage collector? Has a gestalt of defensive programming against this kind of thing emerged? Surely programmers accustomed to RAII must learn lessons when in the presence of GC.

  • justin
    c++ memory-management destructor smart-pointers raii
    I’m writing a C++ destructor (I hope that’s the right term; I’m new to C++) and I’m not positive on what exactly I need to garbage collect. Let’s say I have 2 pointers as instance variables do I need to garbage collect them? What about if I have an object as an instance variable? Or a pointer to an object?I’m just a little fuzzy on what exactly needs to be deleted and what is automatically cleaned up. Thanks

  • Gangadhar
    c++ memory raii memory-deallocation
    Why must we use destructors to de-allocate memory in c++, As we can use delete or delete[] Is it not true that all the memory used up by a program is released when the program terminates.

  • Motti

  • piotrus
    c++ exception exception-handling stack raii
    In wikipedia we read:Resource Acquisition Is Initialization RAII is a programming idiomused in several object-oriented languages like C++, D, Ada and Vala.The technique was invented by Bjarne Stroustrup to deal with resourceallocation and deallocation in C++. In this language, the only codethat can be guaranteed to be executed after an exception is thrown arethe destructors of objects residing on the stack.I don’t want to be over pedantic, whatever, but I really am not sure how to interpret this

  • sharptooth
    c++ raii
    It’s often needed to accomplish the following task: change the state of something, do action, then change the state back to original. For example, in Win32 GDI it’s needed to change background color, then do some drawing, then change the color back.It can be either done directly:COLORREF oldColor = SetBkColor( deviceContext, newColor ); drawStuff( deviceContext ); SetBkColor( deviceContext, oldColor );or via a bracket class that would do the forward change in the constructor and the backward cha

  • decimus phostle
    c++ exception exception-handling raii stack-unwinding
    TIL that my notions of the ‘inter-twining’ (for the lack of a better word) of RAII & stack-unwinding are/were quite(if not completely) wrong. My understanding was that using RAII, guarded against any/all resource leaks – even ones potentially caused by unhandled exceptions. However writing this test program and subsequently stumbling upon this article/documentation, made me realize that stack unwinding would only cause the RAII-enabled resource deallocation to kick in for automatic’s within

  • bames53
    c++ exception c++11 raii nested-exceptions
    So the way to nest exceptions in C++ using std::nested_exception is:void foo() {try {// code that might throwstd::ifstream file(“nonexistent.file”);file.exceptions(std::ios_base::failbit);}catch(…) {std::throw_with_nested(std::runtime_error(“foo failed”));} }But this technique uses explicit try/catch blocks at every level where one wishes to nest exceptions, which is ugly to say the least.RAII, which Jon Kalb expands as “responsibility acquisition is initialization”, is a much cleaner way to d

  • John Millikin
    ruby resources destructor raii finalizer
    I know it’s by design that you can’t control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.However is the ruby idiom for C++’s RAII (Resources are initialized in constructor, closed in destructor)? How do people manage resources used inside objects even when errors or exceptions happen?Using ensure works:f = File.open(“testfile”) begin# .. process rescue# .. handle error ensuref.close unless f.nil? endbut users of the class have to remem

  • jalf
    c++ raii finally
    Bjarne Stroustrup writes in his C++ Style and Technique FAQ, emphasis mine:Because C++ supports an alternative that is almost always better: The “resource acquisition is initialization” technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object’s destructor will release the resource. That way, the programmer cannot forget to release the resource. For example:class File_handle {FILE* p; public:File_handle(const char* n, const char* a){

  • LiKao
    c++ exception destructor raii
    I have a class that is using RAII for cleanup in case something goes wrong. This means the class contains a flag, that tells it whether the work has been completed, and if this flag is not set when the constructor is called it is performing it’s cleanup tasks and produces a log messages. Now I would like this class to become one step more clever, i.e. it should find out, if the error happened, because the work was abborted (i.e. an exception was thrown and the destructor got called) or because s

  • John
    c++ exception raii
    I’m just getting started with RAII in C++ and set up a little test case. Either my code is deeply confused, or RAII is not working! (I guess it is the former).If I run:#include <exception> #include <iostream> class A { public:A(int i) { i_ = i; std::cout << “A ” << i_ << ” constructed” << std::endl; }~A() { std::cout << “A ” << i_ << ” destructed” << std::endl; } private:int i_; };int main(void) {A a1(1);A a2(2);throw std::exception();r

  • DanDan
    c++ shared-ptr raii
    I’m creating a wrapper for a HANDLE that does not work with DuplicateHandle, so instead I am trying to wrap the handle in a shared_ptr.Imagine the following code:class CWrapper { public:CWrapper() :m_pHandle(new HANDLE, &CWrapper::Close){//code to open handle}private:void Close() { //code to close handle}std::shared_ptr<HANDLE> m_pHandle; }I have also tried creating close with a HANDLE parameter (not ideal). Either way, I get the compiler error “Term does not evaluate to a function ta

  • 8 revsAssaf Lavie
    c++ exception raii destructor
    The more we use RAII in C++, the more we find ourselves with destructors that do non-trivial deallocation. Now, deallocation (finalization, however you want to call it) can fail, in which case exceptions are really the only way to let anybody upstairs know of our deallocation problem. But then again, throwing-destructors are a bad idea because of the possibility of exceptions being thrown during stack unwinding. std::uncaught_exception() lets you know when that happens, but not much more, so asi

  • Skurmedel
    c++ raii
    In the C++ code below, am I guaranteed that the ~obj() destructor will be called after the // More code executes? Or is the compiler allowed to destruct the obj object earlier if it detects that it’s not used?{SomeObject obj;… // More code }I’d like to use this technique to save me having to remember to reset a flag at the end of the block, but I need the flag to remain set for the whole block.

  • skaffman
    c++ raii signal-handling longjmp
    So I have a library (not written by me) which unfortunately uses abort() to deal with certain errors. At the application level, these errors are recoverable so I would like to handle them instead of the user seeing a crash. So I end up writing code like this:static jmp_buf abort_buffer; static void abort_handler(int) {longjmp(abort_buffer, 1); // perhaps siglongjmp if available.. }int function(int x, int y) {struct sigaction new_sa;struct sigaction old_sa;sigemptyset(&new_sa.sa_mask);new_sa.

  • bsruth
    c++ raii shared-ptr
    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_p

  • Lightness Races in Orbit

  • rodrigo
    c++ destructor raii
    When I wrap “raw” resources in a C++ class, in destructor code I usually simply release the allocated resource(s), without paying attention to additional steps like zeroing out pointers, etc. e.g.:class File { public:…~File(){if (m_file != NULL)fclose(m_file);}private:FILE * m_file; };I wonder if this code style contains a potential bug: i.e. is it possible that a destructor is called more than once? In this case, the right thing to do in the destructor would be to clear pointers to avoid doub

  • Loki Astari
    c++ exception destructor raii
    Most people say never throw an exception out of a destructor – doing so results in undefined behavior. Stroustrup makes the point that “the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails… There is really no good way to protect against exceptions thrown from destructors, so the library makes no guarantees if an element destructor throws” (from Appendix E3.2).This article seems to say otherwis

Web site is in building