Search Results

Search found 44 results on 2 pages for 'raii'.

Page 1/2 | 1 2  | Next Page >

  • Why can't Java/C# implement RAII?

    - by mike30
    Question: Why can't Java/C# implement RAII? Clarification: I am aware the garbage collector is not deterministic. So with the current language features it is not possible for an object's Dispose() method to be called automatically on scope exit. But could such a deterministic feature be added? My understanding: I feel an implementation of RAII must satisfy two requirements: 1. The lifetime of a resource must be bound to a scope. 2. Implicit. The freeing of the resource must happen without an explicit statement by the programmer. Analogous to a garbage collector freeing memory without an explicit statement. The "implicitness" only needs to occur at point of use of the class. The class library creator must of course explicitly implement a destructor or Dispose() method. Java/C# satisfy point 1. In C# a resource implementing IDisposable can be bound to a "using" scope: void test() { using(Resource r = new Resource()) { r.foo(); }//resource released on scope exit } This does not satisfy point 2. The programmer must explicitly tie the object to a special "using" scope. Programmers can (and do) forget to explicitly tie the resource to a scope, creating a leak. In fact the "using" blocks are converted to try-finally-dispose() code by the compiler. It has the same explicit nature of the try-finally-dispose() pattern. Without an implicit release, the hook to a scope is syntactic sugar. void test() { //Programmer forgot (or was not aware of the need) to explicitly //bind Resource to a scope. Resource r = new Resource(); r.foo(); }//resource leaked!!! I think it is worth creating a language feature in Java/C# allowing special objects that are hooked to the stack via a smart-pointer. The feature would allow you to flag a class as scope-bound, so that it always is created with a hook to the stack. There could be a options for different for different types of smart pointers. class Resource - ScopeBound { /* class details */ void Dispose() { //free resource } } void test() { //class Resource was flagged as ScopeBound so the tie to the stack is implicit. Resource r = new Resource(); //r is a smart-pointer r.foo(); }//resource released on scope exit. I think implicitness is "worth it". Just as the implicitness of garbage collection is "worth it". Explicit using blocks are refreshing on the eyes, but offer no semantic advantage over try-finally-dispose(). Is it impractical to implement such a feature into the Java/C# languages? Could it be introduced without breaking old code?

    Read the article

  • Please help us non-C++ developers understand what RAII is

    - by Charlie Flowers
    Another question I thought for sure would have been asked before, but I don't see it in the "Related Questions" list. Could you C++ developers please give us a good description of what RAII is, why it is important, and whether or not it might have any relevance to other languages? I do know a little bit. I believe it stands for "Resource Acquisition is Initialization". However, that name doesn't jive with my (possibly incorrect) understanding of what RAII is: I get the impression that RAII is a way of initializing objects on the stack such that, when those variables go out of scope, the destructors will automatically be called causing the resources to be cleaned up. So why isn't that called "using the stack to trigger cleanup" (UTSTTC:)? How do you get from there to "RAII"? And how can you make something on the stack that will cause the cleanup of something that lives on the heap? Also, are there cases where you can't use RAII? Do you ever find yourself wishing for garbage collection? At least a garbage collector you could use for some objects while letting others be managed? Thanks.

    Read the article

  • RAII tutorial for c++

    - by Joe Bloggs
    Hi. I'd like to learn how to use RAII in c++. I think I know what it is, but have no idea how to implement it in my programs. A quick google search did not show any nice tutorials. Does any one have any nice links to teach me RAII?

    Read the article

  • when was RAII added to C++

    - by Magnus
    I recently learned about the wonderful memory management technique of RAII, which seems so much cleaner than the new/delete headache I learned in school years ago (I haven't looked at much C++ during the intervening years). I'm trying to track down when this great technique was added to C++. Was it always there and I just missed the memo? What's the oldest version of the C++ standard which supports RAII?

    Read the article

  • Howto mix TDD and RAII

    - by f4
    I'm trying to make extensive tests for my new project but I have a problem. Basically I want to test MyClass. MyClass makes use of several other class which I don't need/want to do their job for the purpose of the test. So I created mocks (I use gtest and gmock for testing) But MyClass instantiate everything it needs in it's constructor and release it in the destructor. That's RAII I think. So I thought, I should create some kind of factory, which creates everything and gives it to MyClass's constructor. That factory could have it's fake for testing purposes. But's thats no longer RAII right? Then what's the good solution here?

    Read the article

  • Automatically release resources RAII-style in Perl

    - by Philip Potter
    Say I have a resource (e.g. a filehandle or network socket) which has to be freed: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!"; Suppose that process might die. Then the code block exits early, and $fh doesn't get closed. I could explicitly check for errors: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error; but this kind of code is notoriously difficult to get right, and only gets more complicated when you add more resources. In C++ I would use RAII to create an object which owns the resource, and whose destructor would free it. That way, I don't have to remember to free the resource, and resource cleanup happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately in Perl a DESTROY method is unsuitable for this purpose as there are no guarantees for when it will be called. Is there a Perlish way to ensure resources are automatically freed like this even in the presence of exceptions? Or is explicit error checking the only option?

    Read the article

  • Can lazy loading be considered an example of RAII?

    - by codemonkey
    I have been catching up on my c++ lately, after a couple years of exclusive Objective-C on iOS, and the topic that comes up most on 'new style' c++ is RAII To make sure I understand RAII concept correctly, would you consider Objective-C lazy loading property accessors a type of RAII? For example, check the following access method - (NSArray *)items { if(_items==nil) { _items=[[NSArray alloc] initWithCapacity:10]; } return _items } Would this be considered an example of RAII? If not, can you please explain where I'm mistaken?

    Read the article

  • resource acquisition is initialization "RAII"

    - by hitech
    in the example below class X{ int *r; public: X(){cout<< X is created ; r new int[10]; } ~X(){cout<< X is destroyed ; delete [] r; } }; class Y { public: Y(){ X x; throw 44; } ~Y(){cout<< Y is destroyed ;} }; I got this example of RAII from one site and ave some doubts. please help. in the contructor of x we are not considering the scenation "if the memory allocation fails" . Here for the destructor of Y is safe as in y construcotr is not allocating any memory. what if we need to do some memory allocation also in y constructor?

    Read the article

  • What happens when we combine RAII and GOTO ?

    - by Robert Gould
    I'm wondering, for no other purpose than pure curiosity (because no one SHOULD EVER write code like this!) about how the behavior of RAII meshes with the use of Goto (lovely idea isn't it). class Two { public: ~Two() { printf("2,"); } }; class Ghost { public: ~Ghost() { printf(" BOO! "); } }; void foo() { { Two t; printf("1,"); goto JUMP; } Ghost g; JUMP: printf("3"); } int main() { foo(); } When running the following code in VS2005 I get the following output: 1,2,3 BOO! However I imagined, guessed, hoped that 'BOO!' wouldn't actually appear as the Ghost should have never been instantiated (IMHO, because I don't know the actual expected behavior of this code). Any Guru out there knows what's up? Just realized that if I instantiate an explicit constructor for Ghost the code doesn't compile... class Ghost { public: Ghost() { printf(" HAHAHA! "); } ~Ghost() { printf(" BOO! "); } }; Ah, the mystery ...

    Read the article

  • Did the developers of Java conciously abandon RAII?

    - by JoelFan
    As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII). In particular, I have discovered that the C# idiom: using (my dbConn = new DbConnection(connStr) { // do stuff with dbConn } has the C++ equivalent: { DbConnection dbConn(connStr); // do stuff with dbConn } meaning that remembering to enclose the use of resources like DbConnection in a using block is unnecessary in C++ ! This seems to a major advantage of C++. This is even more convincing when you consider a class that has an instance member of type DbConnection, for example class Foo { DbConnection dbConn; // ... } In C# I would need to have Foo implement IDisposable as such: class Foo : IDisposable { DbConnection dbConn; public void Dispose() { dbConn.Dispose(); } } and what's worse, every user of Foo would need to remember to enclose Foo in a using block, like: using (var foo = new Foo()) { // do stuff with "foo" } Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII? (Similarly, did Stroustrup fully appreciate the significance of RAII?)

    Read the article

  • Better way to write an object generator for an RAII template class?

    - by Dan
    I would like to write an object generator for a templated RAII class -- basically a function template to construct an object using type deduction of parameters so the types don't have to be specified explicitly. The problem I foresee is that the helper function that takes care of type deduction for me is going to return the object by value, which will result in a premature call to the RAII destructor when the copy is made. Perhaps C++0x move semantics could help but that's not an option for me. Anyone seen this problem before and have a good solution? This is what I have: template<typename T, typename U, typename V> class FooAdder { private: typedef OtherThing<T, U, V> Thing; Thing &thing_; int a_; // many other members public: FooAdder(Thing &thing, int a); ~FooAdder(); void foo(T t, U u); void bar(V v); }; The gist is that OtherThing has a horrible interface, and FooAdder is supposed to make it easier to use. The intended use is roughly like this: FooAdder(myThing, 2) .foo(3, 4) .foo(5, 6) .bar(7) .foo(8, 9); The FooAdder constructor initializes some internal data structures. The foo and bar methods populate those data structures. The ~FooAdder dtor wraps things up and calls a method on thing_, taking care of all the nastiness. That would work fine if FooAdder wasn't a template. But since it is, I would need to put the types in, more like this: FooAdder<Abc, Def, Ghi>(myThing, 2) ... That's annoying, because the types can be inferred based on myThing. So I would prefer to create a templated object generator, similar to std::make_pair, that will do the type deduction for me. Something like this: template<typename T, typename U, typename V> FooAdder<T, U, V> AddFoo(Thing &thing, int a) { return FooAdder<T, U, V>(thing, a); } That seems problematic: because it returns by value, the stack temporary object will be destructed, which will cause the RAII dtor to run prematurely. One thought I had was to give FooAdder a copy ctor with move semantics, kinda like std::auto_ptr. But I would like to do this without dynamic memory allocation, so I thought the copy ctor could set a flag within FooAdder indicating the dtor shouldn't do the wrap-up. Like this: FooAdder(FooAdder &rhs) // Note: rhs is not const : thing_(rhs.thing_) , a_(rhs.a_) , // etc... lots of other members, annoying. , moved(false) { rhs.moved = true; } ~FooAdder() { if (!moved) { // do whatever it would have done } } Seems clunky. Anyone got a better way?

    Read the article

  • How can I automatically release resources RAII-style in Perl?

    - by Philip Potter
    Say I have a resource (e.g. a filehandle or network socket) which has to be freed: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!"; Suppose that process might die. Then the code block exits early, and $fh doesn't get closed. I could explicitly check for errors: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error; but this kind of code is notoriously difficult to get right, and only gets more complicated when you add more resources. In C++ I would use RAII to create an object which owns the resource, and whose destructor would free it. That way, I don't have to remember to free the resource, and resource cleanup happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately in Perl a DESTROY method is unsuitable for this purpose as there are no guarantees for when it will be called. Is there a Perlish way to ensure resources are automatically freed like this even in the presence of exceptions? Or is explicit error checking the only option?

    Read the article

  • Using boost locks for RAII access to a semaphore

    - by dan
    Suppose I write a C++ semaphore class with an interface that models the boost Lockable concept (i.e. lock(); unlock(); try_lock(); etc.). Is it safe/recommended to use boost locks for RAII access to such an object? In other words, do boost locks (and/or other related parts of the boost thread library) assume that the Lockable concept will only be modeled by mutex-like objects which are locked and unlocked from the same thread? My guess is that it should be OK to use a semaphore as a model for Lockable. I've browsed through some of the boost source and it "seems" OK. The locks don't appear to store explicit references to this_thread or anything like that. Moreover, the Lockable concept doesn't have any function like whichThreadOwnsMe(). It also looks like I should even be able to pass a boost::unique_lock<MySemaphore> reference to boost::condition_variable_any::wait. However, the documentation is not explicitly clear about the requirements. To illustrate what I mean, consider a bare-bones binary semaphore class along these lines: class MySemaphore{ bool locked; boost::mutex mx; boost::condition_variable cv; public: void lock(){ boost::unique_lock<boost::mutex> lck(mx); while(locked) cv.wait(lck); locked=true; } void unlock(){ { boost::lock_guard<boost::mutex> lck(mx); if(!locked) error(); locked=false; } cv.notify_one(); } // bool try_lock(); void error(); etc. } Now suppose that somewhere, either on an object or globally, I have MySemaphore sem; I want to lock and unlock it using RAII. Also I want to be able to "pass" ownership of the lock from one thread to another. For example, in one thread I execute void doTask() { boost::unique_lock<MySemaphore> lock(sem); doSomeWorkWithSharedObject(); signalToSecondThread(); waitForSignalAck(); lock.release(); } While another thread is executing something like { waitForSignalFromFirstThread(); ackSignal(); boost::unique_lock<MySemaphore>(sem,boost::adopt_lock_t()); doMoreWorkWithSameSharedObject(); } The reason I am doing this is that I don't want anyone else to be able to get the lock on sem in between the time that the first thread executes doSomeWorkWithSharedObject() and the time the second executes doMoreWorkWithSameSharedObject(). Basically, I'm splitting one task into two parts. And the reason I'm splitting the task up is because (1) I want the first part of the task to get started as soon as possible, (2) I want to guarantee that the first part is complete before doTask() returns, and (3) I want the second, more time-consuming part of the task to be completed by another thread, possibly chosen from a pool of slave threads that are waiting around to finish tasks that have been started by master threads. NOTE: I recently posted this same question (sort of) here http://stackoverflow.com/questions/2754884/unlocking-a-mutex-from-a-different-thread-c but I confused mutexes with semaphores, and so the question about using boost locks didn't really get addressed.

    Read the article

  • RAII: Initializing data member in const method

    - by Thomas Matthews
    In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable (non-const) function to initialize a data member. Example: Loading from a data base struct MyClass { int get_value(void) const; private: void load_from_database(void); // Loads the data member from database. int m_value; }; int MyClass :: get_value(void) const { static bool value_initialized(false); if (!value_initialized) { // The compiler complains about this call because // the method is non-const and called from a const // method. load_from_database(); } return m_value; } My primitive solution is to declare the data member as mutable. I would rather not do this, because it suggests that other methods can change the member. How would I cast the load_from_database() statement to get rid of the compiler errors?

    Read the article

  • Resource Acquisition is Initialization in C#

    - by codeWithoutFear
    Resource Acquisition Is Initialization (RAII) is a pattern I grew to love when working in C++.  It is perfectly suited for resource management such as matching all those pesky new's and delete's.  One of my goals was to limit the explicit deallocation statements I had to write.  Often these statements became victims of run-time control flow changes (i.e. exceptions, unhappy path) or development-time code refactoring. The beauty of RAII is realized by tying your resource creation (acquisition) to the construction (initialization) of a class instance.  Then bind the resource deallocation to the destruction of that instance.  That is well and good in a language with strong destructor semantics like C++, but languages like C# that run on garbage-collecting runtimes don't provide the same instance lifetime guarantees. Here is a class and sample that combines a few features of C# to provide an RAII-like solution: using System; namespace RAII { public class DisposableDelegate : IDisposable { private Action dispose; public DisposableDelegate(Action dispose) { if (dispose == null) { throw new ArgumentNullException("dispose"); } this.dispose = dispose; } public void Dispose() { if (this.dispose != null) { Action d = this.dispose; this.dispose = null; d(); } } } class Program { static void Main(string[] args) { Console.Out.WriteLine("Some resource allocated here."); using (new DisposableDelegate(() => Console.Out.WriteLine("Resource deallocated here."))) { Console.Out.WriteLine("Resource used here."); throw new InvalidOperationException("Test for resource leaks."); } } } } The output of this program is: Some resource allocated here. Resource used here. Unhandled Exception: System.InvalidOperationException: Test for resource leaks. at RAII.Program.Main(String[] args) in c:\Dev\RAII\RAII\Program.cs:line 40 Resource deallocated here. Code without fear! --Don

    Read the article

  • Throwing Exception in CTOR and Smart Pointers

    - by David Relihan
    Is it OK to have the following code in my constructor to load an XML document into a member variable - throwing to caller if there are any problems: MSXML2::IXMLDOMDocumentPtr m_docPtr; //member Configuration() { try { HRESULT hr = m_docPtr.CreateInstance(__uuidof(MSXML2::DOMDocument40)); if ( SUCCEEDED(hr)) { m_docPtr->loadXML(CreateXML()); } else { //throw exception to caller } } catch(...) { //throw exception to caller } } Based on Scott Myers RAII implementations in More Effective C++ I believe I am alright in just allowing exceptions to be thrown from CTOR as I am using a smart pointer(IXMLDOMDocumentPtr). Let me know what you think....

    Read the article

  • Is this a good way to manage initializations of COM?

    - by BillyONeal
    Hello everyone :) I'm very new to anything involving Component Object Model, and I'm wondering if this method of managing calls to CoInitalize/CoUninitalize makes sense: COM.hpp: #pragma once namespace WindowsAPI { namespace ComponentObjectModel { class COM { COM(); ~COM(); public: static void Setup(); }; }} COM.cpp: #include <Windows.h> #include "COM.hpp" namespace WindowsAPI { namespace ComponentObjectModel { COM::COM() { if (CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) != S_OK) throw std::runtime_error("Couldn't start COM!"); } COM::~COM() { CoUninitialize(); } void COM::Setup() { static COM instance; } }} Then any component that needs COM just calls COM::Setup() and forgets about it. Does this make sense or am I breaking any "rules" of COM?

    Read the article

  • Destructors not called when native (C++) exception propagates to CLR component

    - by Phil Nash
    We have a large body of native C++ code, compliled into DLLs. Then we have a couple of dlls containing C++/CLI proxy code to wrap the C++ interfaces. On top of that we have C# code calling into the C++/CLI wrappers. Standard stuff, so far. But we have a lot of cases where native C++ exceptions are allowed to propagate to the .Net world and we rely on .Net's ability to wrap these as System.Exception objects and for the most part this works fine. However we have been finding that destructors of objects in scope at the point of the throw are not being invoked when the exception propagates! After some research we found that this is a fairly well known issue. However the solutions/ workarounds seem less consistent. We did find that if the native code is compiled with /EHa instead of /EHsc the issue disappears (at least in our test case it did). However we would much prefer to use /EHsc as we translate SEH exceptions to C++ exceptions ourselves and we would rather allow the compiler more scope for optimisation. Are there any other workarounds for this issue - other than wrapping every call across the native-managed boundary in a (native) try-catch-throw (in addition to the C++/CLI layer)?

    Read the article

  • Unit Testing Private Method in Resource Managing Class (C++)

    - by BillyONeal
    I previously asked this question under another name but deleted it because I didn't explain it very well. Let's say I have a class which manages a file. Let's say that this class treats the file as having a specific file format, and contains methods to perform operations on this file: class Foo { std::wstring fileName_; public: Foo(const std::wstring& fileName) : fileName_(fileName) { //Construct a Foo here. }; int getChecksum() { //Open the file and read some part of it //Long method to figure out what checksum it is. //Return the checksum. } }; Let's say I'd like to be able to unit test the part of this class that calculates the checksum. Unit testing the parts of the class that load in the file and such is impractical, because to test every part of the getChecksum() method I might need to construct 40 or 50 files! Now lets say I'd like to reuse the checksum method elsewhere in the class. I extract the method so that it now looks like this: class Foo { std::wstring fileName_; static int calculateChecksum(const std::vector<unsigned char> &fileBytes) { //Long method to figure out what checksum it is. } public: Foo(const std::wstring& fileName) : fileName_(fileName) { //Construct a Foo here. }; int getChecksum() { //Open the file and read some part of it return calculateChecksum( something ); } void modifyThisFileSomehow() { //Perform modification int newChecksum = calculateChecksum( something ); //Apply the newChecksum to the file } }; Now I'd like to unit test the calculateChecksum() method because it's easy to test and complicated, and I don't care about unit testing getChecksum() because it's simple and very difficult to test. But I can't test calculateChecksum() directly because it is private. Does anyone know of a solution to this problem?

    Read the article

  • When is it appropriate to use C++ exceptions?

    - by krebstar
    I'm trying to design a class that needs to dynamically allocate some memory.. I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me.. Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully? Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail.. EDIT: The consensus seems to be that running out of memory IS an exceptional case. Will see how to go about this.. Thanks.. :)

    Read the article

  • How to handle failure to release a resource which is contained in a smart pointer?

    - by cj
    How should an error during resource deallocation be handled, when the object representing the resource is contained in a shared pointer? Smart pointers are a useful tool to manage resources safely. Examples of such resources are memory, disk files, database connections, or network connections. // open a connection to the local HTTP port boost::shared_ptr<Socket> socket = Socket::connect("localhost:80"); In a typical scenario, the class encapsulating the resource should be noncopyable and polymorphic. A good way to support this is to provide a factory method returning a shared pointer, and declare all constructors non-public. The shared pointers can now be copied from and assigned to freely. The object is automatically destroyed when no reference to it remains, and the destructor then releases the resource. /** A TCP/IP connection. */ class Socket { public: static boost::shared_ptr<Socket> connect(const std::string& address); virtual ~Socket(); protected: Socket(const std::string& address); private: // not implemented Socket(const Socket&); Socket& operator=(const Socket&); }; But there is a problem with this approach. The destructor must not throw, so a failure to release the resource will remain undetected. A common way out of this problem is to add a public method to release the resource. class Socket { public: virtual void close(); // may throw // ... }; Unfortunately, this approach introduces another problem: Our objects may now contain resources which have already been released. This complicates the implementation of the resource class. Even worse, it makes it possible for clients of the class to use it incorrectly. The following example may seem far-fetched, but it is a common pitfall in multi-threaded code. socket->close(); // ... size_t nread = socket->read(&buffer[0], buffer.size()); // wrong use! Either we ensure that the resource is not released before the object is destroyed, thereby losing any way to deal with a failed resource deallocation. Or we provide a way to release the resource explicitly during the object's lifetime, thereby making it possible to use the resource class incorrectly. There is a way out of this dilemma. But the solution involves using a modified shared pointer class. These modifications are likely to be controversial. Typical shared pointer implementations, such as boost::shared_ptr, require that no exception be thrown when their object's destructor is called. Generally, no destructor should ever throw, so this is a reasonable requirement. These implementations also allow a custom deleter function to be specified, which is called in lieu of the destructor when no reference to the object remains. The no-throw requirement is extended to this custom deleter function. The rationale for this requirement is clear: The shared pointer's destructor must not throw. If the deleter function does not throw, nor will the shared pointer's destructor. However, the same holds for other member functions of the shared pointer which lead to resource deallocation, e.g. reset(): If resource deallocation fails, no exception can be thrown. The solution proposed here is to allow custom deleter functions to throw. This means that the modified shared pointer's destructor must catch exceptions thrown by the deleter function. On the other hand, member functions other than the destructor, e.g. reset(), shall not catch exceptions of the deleter function (and their implementation becomes somewhat more complicated). Here is the original example, using a throwing deleter function: /** A TCP/IP connection. */ class Socket { public: static SharedPtr<Socket> connect(const std::string& address); protected: Socket(const std::string& address); virtual Socket() { } private: struct Deleter; // not implemented Socket(const Socket&); Socket& operator=(const Socket&); }; struct Socket::Deleter { void operator()(Socket* socket) { // Close the connection. If an error occurs, delete the socket // and throw an exception. delete socket; } }; SharedPtr<Socket> Socket::connect(const std::string& address) { return SharedPtr<Socket>(new Socket(address), Deleter()); } We can now use reset() to free the resource explicitly. If there is still a reference to the resource in another thread or another part of the program, calling reset() will only decrement the reference count. If this is the last reference to the resource, the resource is released. If resource deallocation fails, an exception is thrown. SharedPtr<Socket> socket = Socket::connect("localhost:80"); // ... socket.reset();

    Read the article

  • C/C++ macro/template blackmagic to generate unique name.

    - by anon
    Macros are fine. Templates are fine. Pretty much whatever it works is fine. The example is OpenGL; but the technique is C++ specific and relies on no knowledge of OpenGL. Precise problem: I want an expression E; where I do not have to specify a unique name; such that a constructor is called where E is defined, and a destructor is called where the block E is in ends. For example, consider: class GlTranslate { GLTranslate(float x, float y, float z); { glPushMatrix(); glTranslatef(x, y, z); } ~GlTranslate() { glPopMatrix(); } }; Manual solution: { GlTranslate foo(1.0, 0.0, 0.0); // I had ti give it a name ..... } // auto popmatrix Now, I have this not only for glTranslate, but lots of other PushAttrib/PopAttrib calls too. I would prefer not to have to come up with a unique name for each var. Is there some trick involving macros templates ... or something else that will automatically create a variable who's constructor is called at point of definition; and destructor called at end of block? Thanks!

    Read the article

  • What wrapper class in C++ should I use for automated resource management?

    - by Vilx-
    I'm a C++ amateur. I'm writing some Win32 API code and there are handles and weirdly compositely allocated objects aplenty. So I was wondering - is there some wrapper class that would make resource management easier? For example, when I want to load some data I open a file with CreateFile() and get a HANDLE. When I'm done with it, I should call CloseHandle() on it. But for any reasonably complex loading function there will be dozens of possible exit points, not to mention exceptions. So it would be great if I could wrap the handle in some kind of wrapper class which would automatically call CloseHandle() once execution left the scope. Even better - it could do some reference counting so I can pass it around in and out of other functions, and it would release the resource only when the last reference left scope. The concept is simple - but is there something like that in the standard library? I'm using Visual Studio 2008, by the way, and I don't want to attach a 3rd party framework like Boost or something.

    Read the article

  • Why Garbage Collection if smart pointers are there

    - by Gulshan
    This days, so many languages are garbage collected. Even it is available for C++ by third parties. But, C++ has RAII and smart pointers. So, what's the point of using garbage collection? Is it doing something extra? And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there be still any need of garbage collectors? If no, then why this is not so?

    Read the article

1 2  | Next Page >