[Info-vax] BASIC (and Horizon)
Dan Cross
cross at spitfire.i.gajendra.net
Wed Jan 31 15:41:32 EST 2024
In article <upe3ib$1kker$1 at dont-email.me>,
Arne Vajhøj <arne at vajhoej.dk> wrote:
>On 1/31/2024 11:17 AM, Scott Dorsey wrote:
>> Michael S <already5chosen at yahoo.com> wrote:
>>>
>>> The third option, the one I like least (an understatement) is use of
>>> exceptions. Despite my personal preferences, it's quite popular.
>>
>> Exceptions can be very elegant or very inelegant... and it is entirely
>> possible to have an exception that doesn't clean anything up at all and
>> just exits and lets the operating system deal with the memory. On many
>> systems this is a great idea because being able to exit quickly on a failure
>> is more important than people give it credit for. On some other systems
>> that have memory management issues it can lead to leakage.
>
>It is probably a bit easier to implement exceptions in languages
>with garbage collection and a lot easier for developers to avoid
>memory leak bugs.
>
>$ type mem.cpp
>#include <iostream>
>#include <string>
>
>using namespace std;
>
>class X
>{
>private:
> string id;
>public:
> X(string id) { this->id = id; cout << "Allocate " << id << endl; }
> virtual ~X() { cout << "Deallocate " << id << endl; }
>};
>
>void f2()
>{
> throw "Houston we have a problem";
>}
>
>void f1()
>{
> X o2("o2");
> X *o3 = new X("o3");
> f2();
> delete o3;
>}
>
>int main()
>{
> try
> {
> X o1("o1");
> f1();
> }
> catch(char *ex)
> {
> cout << ex << endl;
> }
> return 0;
>}
>
>$ cxx mem.cpp
>$ cxxlink mem
>link mem
>$ run mem
>Allocate o1
>Allocate o2
>Allocate o3
>Deallocate o2
>Deallocate o1
>Houston we have a problem
>$
>
>We see that o2 did get deallocated, but o3 did not get deallocated.
This is well-known in older C++ code; since C++11 one should be
using `std::unique_ptr<T>` to avoid this sort of issue. Code
using an older dialect could look at something like the
venerable ScopeGuard as a defensive technique to guard against
leaks.
https://www.drdobbs.com/article/print?articleId=184403758&siteSectionName=cpp
- Dan C.
More information about the Info-vax
mailing list