Re: C# vs. C++ (was Re: UNICODE conversion)



"David Lowndes" <DavidL@xxxxxxxxxxxxxxx> wrote in message
news:5ntit39eebpgv40spn55oprvdk92s44et8@xxxxxxxxxx
...
So if MyObject::foo() opens a file and throws and exception, if it has a
'finally' it can close the file before returning. But if you rely on
MyObject::~MyObject() to close the file, the file may stay open for a long
time after the exception was thrown.

That is the issue in C# as I understand it - but not in C++ (or
C++/CLI) - which is why it's a more elegant language in that respect.


Hmm, maybe I should give an example in C++:


class CMyObject
{
CFile m_file;
CString m_filename; // filename opened into m_file

public:
void foo()
{
try
{
m_file.Open(m_filename);

// Cause divide-by-zero exception
int i = 3 / 0;
}

m_file.Close();
}

void bar()
{
DeleteFile (m_filename);
}
}


int main()
{
CMyObject object;
try
{
object.foo();
}
catch(...)
{
// handle divide by 0 error
}

object.bar();
}


So in the above C++ example, foo() throws an exception, and thus the
m_file.Close() is not executed. Then when bar() is called, it tries to
delete the file which was not closed and it fails.


Whereas, in C# using 'finally' this won't happen:

class CMyObject
{
// declarations the same for sake of example;
// I know there is no CFile or CString in .NET!
CFile m_file;
CString m_filename; // filename opened into m_file

public:
void foo()
{
try
{
m_file.Open(m_filename);

// Cause divide-by-zero exception
int i = 3 / 0;
}
finally
{
// Close file in 'finally' to ensure it always executes before
foo() exits
m_file.Close();
}
}

void bar()
{
DeleteFile (m_filename);
}
}

In C#, calling foo() and then bar() properly deletes the file because the
file has been closed prior to DeleteFile() being called.


Thanks,
David



.



Relevant Pages

  • Re: linking C++ functions in a C program
    ... contains one function named foo() which is compiled in C, ... Therefore, no matter how you classify bar(), this program ... void foo; ... guess the compiler can generate two references to foo, one adorned, ...
    (comp.lang.c)
  • Circular dependency - I think..
    ... The header file for FOO is composed of BAR, ... int GetFbk(); ... void ComputeTorquerCmd(); ...
    (comp.lang.cpp)
  • Re: is assignment atomic/thread safe?
    ... void foo() ... with one thread running foo() while another runs bar(). ... and thus no guarantees are made about _when_ any given piece of code will execute. ...
    (comp.lang.java.programmer)
  • Re: Library bug or my fault?
    ... compiled using ARM/Linux cross-compiler and run on an ARM9 target. ... void memcpy ... 29 void cp(const Foo *foo) ... 31 Bar bar; ...
    (comp.lang.c)
  • Re: Building extensibility into an API
    ... Now maybe you think of some cool improvement to foo that you could make, ... foo_v2(int bar, char *baz, long double newparam); ... Each function you write takes an unused void * parameter. ...
    (comp.lang.c)

Loading