POV-Ray : Newsgroups : povray.off-topic : C++ questions : Re: C++ questions Server Time
7 Sep 2024 09:24:17 EDT (-0400)
  Re: C++ questions  
From: Warp
Date: 26 Sep 2008 11:18:53
Message: <48dcfd5c@news.povray.org>
Invisible <voi### [at] devnull> wrote:
> >> [I'm actually surprised that using std::vector doesn't do this already...]
> > 
> >   Doesn't do what?

> Leak like a sieve! ;-)

  The class constructors, assignment and destructor help in automatizing
the internal memory management of the vector.

  You can write your own dynamic data container as a class in the exact
same way as std::vector and the other STL containers, which will be safe
and will automatically manage its memory.

  And not only memory. There are also other resources which can be
automatically managed with classes. Consider this:

void foo()
{
    std::ofstream os("outfile.txt");
    os << "Hello\n";
    bar();
    os << "there.\n";
}

  Note that nowhere is the file actually explicitly *closed*. However,
no open file handles are leaked because it gets closed automatically
because the std::ofstream class handles this resource.

  This is even so even if the function is exited abnormally. For example,
assume that the bar() call throws an exception. If that happens, the
function will be exited immediately (before the "there.\n" string is
written to the file). This is "unexpected" and we didn't take that
possibility into account. However, it doesn't matter: The file will
still be closed and thus no resource leak happens.

  Unless I'm completely mistaken, this is not something you can achieve
in Java. (In Java you have to close files explicitly and catch all
possible exceptions which might otherwise bypass that closing.)

> I've never actually seen a programming environment with manual memory 
> management *and* dynamically resizable collections. The two are usually 
> muturally exclusive.

  Well, it's not like *all* resources in C++ are managed manually.
More precisely, stack-allocated objects are managed automatically. Which
is exactly the reason why automatic management heap-allocated objects
becomes possible through these stack-allocated objects.

> Then again, I'm not really sure what the story is if you try to put 
> user-defined data types into a vector...

  If the user-defined type doesn't allocate memory in itself, or if it
does but manages it properly, there shouldn't be any problems.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.