473,594 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about garbage collection in in vc++ 2005

I was reading a ppt ( http://www.gotdotnet.com/team/pdc/4064/tls310.ppt )
and came aross this statement.

"Users can leverage a destructor. The C++ compiler generates all the Dispose
code automatically, including chaining calls to Dispose. (There is no
Dispose pattern)"

but Dispose can thrown an exception. Is the exception supressed?
Nov 17 '05 #1
9 1246
Hasani (remove nospam from address) wrote:
I was reading a ppt ( http://www.gotdotnet.com/team/pdc/4064/tls310.ppt )
and came aross this statement.

"Users can leverage a destructor. The C++ compiler generates all the
Dispose code automatically, including chaining calls to Dispose. (There
is no Dispose pattern)"

but Dispose can thrown an exception. Is the exception supressed?


Destructors can throw exceptions too. They are not suppressed. Since
destruction is deterministic, most of the time you can handle the exception
yourself. When an exception is thrown from a destructor while another
exception is unwinding the stack, the exceptions are linked together.

Of course, it is recommended that you not throw exceptions from destructors.
(The same is true if you are writing Dispose in other languages.)

--
Brandon Bray, Visual C++ Compiler http://blogs.msdn.com/branbray/
This posting is provided AS IS with no warranties, and confers no rights.
Nov 17 '05 #2
I just want to make sure I'm getting this right.
In the next release of c++.net, lets assume the following code

=============== =============== =

#using <mscorlib.dll >

using namespace System;
using namespace System::Net::So ckets;

public __gc class Foo : public IDisposable
{
public:
Foo()
{
_socket = new
System::Net::So ckets::Socket(A ddressFamily::I nterNetwork,
SocketType::Str eam, ProtocolType::T cp);
_isocket = dynamic_cast<ID isposable*>(soc ket);
}

void IDisposable::Di spose()
{
_isocket->Dispose();
}

~Foo()
{
try
{
Dispose();
}
catch(...)
{
}
}

__property Socket* get_Socket()
{
//TODO: do check to make sure object is not disposed.
return _socket;
}

private:
System::Net::So cket __gc* _socket;
IDisposable __gc* _isocket;
};

int main(int argc, char* argcv[])
{
{
Foo f;
Object __gc* socket = f.Socket;
}
//the desctructor should have been called by now.
return 0;
}

=============== ===========

I'm assuming the the following happen behind the scenes.

1) f.Dispose() will be called automatically in the same thread context in
which f was initialized and no exception handling being performed
if f.dtor() throws an exception.
2) f.dtor() [same text as 1]
3) there is no excpetion handling performed when f.Dispose() and the
f.dtor() is automatically called.
4) the private variable f._socket will not be finalized instantly when
variable, f, goes out of scope. It will be finalized the next time garbage
collection is performed by either the system, or a call to GC::Collect.
5) When I say automatically, this is done at compile time and not runtime.
the compiler adds code to do 1, 2 and 3. 4 would be at runtime.

Thx in advance, I'm just trying to get a solid understanding of this new
feature of c++.net.

Also, if an object contains a finalizer, such as the Regex class. In the
next version of c++, will finalizers be treated as destructors so I can do

Regex __gc* regex = new Regex();
delete regex;

"Brandon Bray [MSFT]" <br******@onlin e.microsoft.com > wrote in message
news:u6******** *****@TK2MSFTNG P12.phx.gbl...
Hasani (remove nospam from address) wrote:
I was reading a ppt ( http://www.gotdotnet.com/team/pdc/4064/tls310.ppt ) and came aross this statement.

"Users can leverage a destructor. The C++ compiler generates all the
Dispose code automatically, including chaining calls to Dispose. (There
is no Dispose pattern)"

but Dispose can thrown an exception. Is the exception supressed?
Destructors can throw exceptions too. They are not suppressed. Since
destruction is deterministic, most of the time you can handle the

exception yourself. When an exception is thrown from a destructor while another
exception is unwinding the stack, the exceptions are linked together.

Of course, it is recommended that you not throw exceptions from destructors. (The same is true if you are writing Dispose in other languages.)

--
Brandon Bray, Visual C++ Compiler http://blogs.msdn.com/branbray/
This posting is provided AS IS with no warranties, and confers no rights.

Nov 17 '05 #3
Hasani (remove nospam from address) wrote:
I'm assuming the the following happen behind the scenes.
First note that in the old syntax, deterministic cleanup is not available.
That is a feature of the new syntax. I'll answer your questions in terms of
the old syntax, and separately call out anything interesting about the new
syntax.

Also, note that in the old syntax ~Class maps to the finalizer of the class
(even though it generates a __dtor method). In the new syntax, ~Class maps
to Dispose (which is the destructor), and !Class maps to the finalizer.
1) f.Dispose() will be called automatically in the same thread context in
which f was initialized and no exception handling being performed if
f.dtor() throws an exception.
Note that F (being a reference class) cannot be instantiated on the stack in
the old syntax. So, if it were created with a __gc pointer, the old syntax
would still allow F::Dispose to be called from the finalizer thread (which
is different than the thread f was created on).

The new syntax does allow F to be created on the stack, in which case its
destructor (i.e. Dispose) will be called at the end of the scope even if an
exception takes place. Thus, the finalizer should never run.
2) f.dtor() [same text as 1]
In the old syntax, if Dispose is not run, the finalizer will. If Dispose is
run, it is very likely that the finalizer will not.

In the new syntax, the C++ generated destructor suppresses finalization.
3) there is no excpetion handling performed when f.Dispose() and the
f.dtor() is automatically called.
The question doesn't make sense. Perhaps you are asking, in the presence of
an exception, does Dispose and dtor get called?

If that is the question, the answer is no (both of the them cannot be
called). Depending on what try/__finally blocks you have in the old syntax,
the Dispose may run. If it does, the finalizer probably will not. If Dispose
doesn't run, the finalizer will run.

In the new syntax, if the type is allocated on the stack, then it will have
its destructor (i.e. Dispose) called if an exception occurs.
4) the private variable f._socket will not be finalized instantly when
variable, f, goes out of scope. It will be finalized the next time garbage
collection is performed by either the system, or a call to GC::Collect.
That is correct. If the destructor does not clean up the Socket (i.e. call
the Socket's destructor), the Socket will be finalized.
5) When I say automatically, this is done at compile time and not runtime.
the compiler adds code to do 1, 2 and 3. 4 would be at runtime.
Yes, the compiler does all of the above in new syntax. If you are using the
old syntax, it does not do this.
Also, if an object contains a finalizer, such as the Regex class. In the
next version of c++, will finalizers be treated as destructors so I can do


No. Finalizers and destructors are two different things. A finalizer gets
called when a destructor was not called. We map destructors to the Dispose
method from IDisposable. So, if you define a destructor in any ref class,
C++ will generate the Dispose pattern for you. It will also chain
destructors as usual. So, using the delete keyword on an object will
ultimately cause the Dispose method to be called.

Because the C++ compiler generates Dispose for you, you cannot write Dispose
yourself. Instead, you need to use destructor syntax.

Hope that helps!

--
Brandon Bray, Visual C++ Compiler http://blogs.msdn.com/branbray/
This posting is provided AS IS with no warranties, and confers no rights.
Nov 17 '05 #4
Brandon Bray [MSFT] wrote:
First note that in the old syntax, deterministic cleanup is not available.
That is a feature of the new syntax. I'll answer your questions in terms of
the old syntax, and separately call out anything interesting about the new
syntax.

Please explain me the following about C++/CLI draft as it is currently:
1) Can we create an object of a ref class in the stack?

ref class test
{
// ...
};

test a;

When this is destroyed at the end of the scope, the memory allocated is
freed or only the destructor is called?
2) When we call delete on a handle pointing to an object in the free
store of a ref type, the destructor is called but is the memory freed?

3) Can we do this?
ref class test
{
// ...
};
// A test in the unmanaged heap
test *p=new test;

delete p;

4) What is the exact reason that templates cannot work with CLI types
and we need special versions of STL facilities?


Regards,

Ioannis Vranos
Nov 17 '05 #5
Ioannis,
Please explain me the following about C++/CLI draft as it is currently:
1) Can we create an object of a ref class in the stack?

ref class test
{
// ...
};

test a;

When this is destroyed at the end of the scope, the memory allocated is
freed or only the destructor is called?
Neither. At least not exactly. If the type implements IDisposable (which in
C++/CLI is created through the destructor syntax ~test), then the object
will be disposed at the end of the scope. If it doesn't, then nothing
happens. In neither case is the memory of the object actually deallocated;
that's left to the GC, as usual.
2) When we call delete on a handle pointing to an object in the free
store of a ref type, the destructor is called but is the memory freed?
IDisposable::Di spose is called, if the object implements that (again,
destructor syntax is now Disposable, while finalizers have a different one).
Again, memory is freed by the GC.
3) Can we do this?
ref class test
{
// ...
};
// A test in the unmanaged heap
test *p=new test;

delete p;
Nope. reference type objects need to be allocated inside the GC heap.
4) What is the exact reason that templates cannot work with CLI types
and we need special versions of STL facilities?


I think you're asking two different questions here. Templates *do* work with
CLI types in C++/CLI. Actually, it is the only language supporting both
generics *and* templates; which is quite powerful.

The second questions is the need for a STL-like facility for GC types, and
that's a different story altogether. I think Ronald Laeremans provided a
much better answer that I could about that a few days ago...

--
Tomas Restrepo
to****@mvps.org
Nov 17 '05 #6
Tomas Restrepo (MVP) wrote:
4) What is the exact reason that templates cannot work with CLI types
and we need special versions of STL facilities?

I think you're asking two different questions here. Templates *do* work with
CLI types in C++/CLI. Actually, it is the only language supporting both
generics *and* templates; which is quite powerful.

The second questions is the need for a STL-like facility for GC types, and
that's a different story altogether. I think Ronald Laeremans provided a
much better answer that I could about that a few days ago...

OK yes, I rephrase the question.

What is the exact reason that templates cannot work with ref types and
we need special versions of STL facilities?


Regards,

Ioannis Vranos
Nov 17 '05 #7
Ioannis Vranos wrote:
What is the exact reason that templates cannot work with ref types and
we need special versions of STL facilities?


Templates can work with ref classes, interfaces, and value classes. That is
a feature we added in Whidbey (it wasn't a limitation of the language, but
rather a limitation of the metadata merge step when linking the program).

We are creating a new STL library specifically for .NET so that it (1) can
be verifiable, (2) interoperate with the Framework libraries, such as
passing a vector to an IList interface, and (3) can pass collections between
assemblies through generics.

Regarding the structure of STL for .NET or for Standard C++, it is the same.

--
Brandon Bray, Visual C++ Compiler http://blogs.msdn.com/branbray/
This posting is provided AS IS with no warranties, and confers no rights.
Nov 17 '05 #8
Brandon Bray [MSFT] wrote:
Ioannis Vranos wrote:
What is the exact reason that templates cannot work with ref types and
we need special versions of STL facilities?

Templates can work with ref classes, interfaces, and value classes. That is
a feature we added in Whidbey (it wasn't a limitation of the language, but
rather a limitation of the metadata merge step when linking the program).

We are creating a new STL library specifically for .NET so that it (1) can
be verifiable, (2) interoperate with the Framework libraries, such as
passing a vector to an IList interface, and (3) can pass collections between
assemblies through generics.

Regarding the structure of STL for .NET or for Standard C++, it is the same.


That's great news!


Regards,

Ioannis Vranos
Nov 17 '05 #9
Thx for the answers. I have another question though. Since in the new
version of c++, the Dispose now links to the destructor, how will this
affect code written in vc7/7.1
Because the C++ compiler generates Dispose for you, you cannot write Dispose yourself. Instead, you need to use destructor syntax.
I am curious as to would would happen if I had a class written in an older
verion of c++ that implements IDisposable, and also has a desctructor? Will
calling delete Class invoke the destructor or the dispose method? I'm
assuming it will invoke the dispose method.

"Brandon Bray [MSFT]" <br******@onlin e.microsoft.com > wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. .. Hasani (remove nospam from address) wrote:
I'm assuming the the following happen behind the scenes.
First note that in the old syntax, deterministic cleanup is not available.
That is a feature of the new syntax. I'll answer your questions in terms

of the old syntax, and separately call out anything interesting about the new
syntax.

Also, note that in the old syntax ~Class maps to the finalizer of the class (even though it generates a __dtor method). In the new syntax, ~Class maps
to Dispose (which is the destructor), and !Class maps to the finalizer.
1) f.Dispose() will be called automatically in the same thread context in which f was initialized and no exception handling being performed if
f.dtor() throws an exception.
Note that F (being a reference class) cannot be instantiated on the stack

in the old syntax. So, if it were created with a __gc pointer, the old syntax
would still allow F::Dispose to be called from the finalizer thread (which
is different than the thread f was created on).

The new syntax does allow F to be created on the stack, in which case its
destructor (i.e. Dispose) will be called at the end of the scope even if an exception takes place. Thus, the finalizer should never run.
2) f.dtor() [same text as 1]
In the old syntax, if Dispose is not run, the finalizer will. If Dispose

is run, it is very likely that the finalizer will not.

In the new syntax, the C++ generated destructor suppresses finalization.
3) there is no excpetion handling performed when f.Dispose() and the
f.dtor() is automatically called.
The question doesn't make sense. Perhaps you are asking, in the presence

of an exception, does Dispose and dtor get called?

If that is the question, the answer is no (both of the them cannot be
called). Depending on what try/__finally blocks you have in the old syntax, the Dispose may run. If it does, the finalizer probably will not. If Dispose doesn't run, the finalizer will run.

In the new syntax, if the type is allocated on the stack, then it will have its destructor (i.e. Dispose) called if an exception occurs.
4) the private variable f._socket will not be finalized instantly when
variable, f, goes out of scope. It will be finalized the next time garbage collection is performed by either the system, or a call to GC::Collect.
That is correct. If the destructor does not clean up the Socket (i.e. call
the Socket's destructor), the Socket will be finalized.
5) When I say automatically, this is done at compile time and not runtime. the compiler adds code to do 1, 2 and 3. 4 would be at runtime.


Yes, the compiler does all of the above in new syntax. If you are using

the old syntax, it does not do this.
Also, if an object contains a finalizer, such as the Regex class. In the
next version of c++, will finalizers be treated as destructors so I can
do
No. Finalizers and destructors are two different things. A finalizer gets
called when a destructor was not called. We map destructors to the Dispose
method from IDisposable. So, if you define a destructor in any ref class,
C++ will generate the Dispose pattern for you. It will also chain
destructors as usual. So, using the delete keyword on an object will
ultimately cause the Dispose method to be called.

Because the C++ compiler generates Dispose for you, you cannot write Dispose yourself. Instead, you need to use destructor syntax.

Hope that helps!

--
Brandon Bray, Visual C++ Compiler http://blogs.msdn.com/branbray/
This posting is provided AS IS with no warranties, and confers no rights.

Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
9359
by: Eric | last post by:
Hi, I'm used to C/C++ where if you "new" something you really need to "delete" it later. Is that also true in javascript? if i do "mydate = new date();" in a function and dont "delete mydate" when the function exits do i have a memory leak or other trouble brewing? ie: function MyFn() { var mydate;
3
4132
by: Ian Taite | last post by:
Hello, I'm exploring why one of my C# .NET apps has "high" memory usage, and whether I can reduce the memory usage. I have an app that wakes up and processes text files into a database periodically. What happens, is that the app reads the contents of a text file line by line into an ArrayList. Each element of the ArrayList is a string representing a record from the file. The ArrayList is then processed, and the arraylist goes out of...
5
2338
by: Charles T. | last post by:
Hi, looking for advance article/books on garbage-collected allocation. thanks, Charles.
34
6395
by: Ville Voipio | last post by:
I would need to make some high-reliability software running on Linux in an embedded system. Performance (or lack of it) is not an issue, reliability is. The piece of software is rather simple, probably a few hundred lines of code in Python. There is a need to interact with network using the socket module, and then probably a need to do something hardware- related which will get its own driver written in C.
4
1549
by: bkazlak | last post by:
Hello, I have a quick question might help me understand garbage collection. let's say I'm having a static collection of objects in one class, so this collection should be cached and present all time. Now if a method in another object clones this collection, when would be the cloned collection eligible for garbage collection? when the method goes out of scope?
36
1894
by: André | last post by:
Hello, I have a c# application that creates a timer to fire every minute using multithreading. On every minute it calls a Ping class that I made using sockets. It creates a new ping class then sets it to null when it’s done. I noticed every time this class gets created I see the memory keeps getting larger. I think I should add Idisposable to my ping class and dispose of the memory
7
2669
by: cmrchs | last post by:
Hi, how do you mark an object for garbage collection in C++.NET 2005 ? MyDbClass^ obj = gcnew MyDbClass(); // Release the object obj = 0; --> COMPILER ERROR obj = nullptr; // nope : this does not mark it for garbage // collection (see help)
7
6419
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
1
2340
by: Crash | last post by:
..Net - All versions I have Essential .Net Vol 1 (Don Box) and the Jeffrey Richter articles on the .NET heap - they are both excellent reads. But I am still unclear on the big pinned memory question: Pinned memory: if I have a block of pinned memory active on the heap when a garbage collection occurs where does the garbage collector set the NextObj pointer? Can the garbage collector/heap allocator logic work around the pinned block...
0
7936
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7874
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8241
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6646
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5738
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5402
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2383
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.