i have assembly in 'c++/cli' implements classes. let assume class of 'sometype'.
now, in application developed in 'c#', following -
while(!console.keyavailable) { using(sometype type = new sometype()) { type.dosomething(); //do } }
would have consequence, memory leaks etc. in situation, if there unhandled exception or such?
i read using
keyword should used class implements idisposable, c++/cli class?
c++/cli not have equivalent of using keyword. took different approach, 1 native c++ programmers expect. familiar common c++ idiom implement deterministic destruction, raii pattern. invoking requires using "stack semantics". works well, syntax requirements pretty obscure.
i'll first show clumsy way, helpful demonstrate syntax differences. lets use streamreader, disposable class in .net:
string^ readtoplinefromfile(string^ path) { streamreader^ reader = gcnew streamreader(path); try { return reader->readline(); } { delete reader; } }
the try/finally makes code exception-safe, if readline() throws exception streamreader object still disposed , lock on file guaranteed released. code c# compiler emits automatically when use using
statement. note use of delete
operator, in effect calls streamreader::dispose() method. compiler won't let write reader->dispose()
, using operator mandatory.
now using version c++/cli compiler supports. invoke stack semantics emulating way native c++ compiler treats c++ object that's allocated on stack. this:
string^ readtoplinefromfile(string^ path) { streamreader reader(path); return reader.readline(); } // <== disposed here
note missing ^ hat on variable name, required when stores reference type reference. intentionally omitting invokes pattern. no explicit gcnew
call required, compiler emits automatically. note no longer use ->
dereference object, use .
the c++/cli compiler automatically generates try/finally blocks delete operator call. emitted @ closing brace of scope block. native c++ compiler it. while looks managed object allocated on stack, that's syntactical illusion, still on gc heap.
syntax different of course, real hangup feature. knowing when use ^ hat , when rely on stack semantics needs learned, takes while.
Comments
Post a Comment