C++ class pointers
-
Suppose a class in C++ has a pointer in it.
class
{
int*x;
}Then what all precautions we need to take regarding handling the pointer?
-
Suppose a class in C++ has a pointer in it.
class
{
int*x;
}Then what all precautions we need to take regarding handling the pointer?
There are two ways of dealing with pointer members: Default Constructor e.g. initialize to NULL or allocate memory Destructor free memory if allocated and the class "owns" the memory Copy Constructor & Assignment Operator Handle them correctly - e.g. free the memory allocated it is good practice to use one class per unmanaged resource.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server. -
There are two ways of dealing with pointer members: Default Constructor e.g. initialize to NULL or allocate memory Destructor free memory if allocated and the class "owns" the memory Copy Constructor & Assignment Operator Handle them correctly - e.g. free the memory allocated it is good practice to use one class per unmanaged resource.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server.peterchen wrote:
it is good practice to use one class per unmanaged resource.
Since when? I know it sounds good in theory and even I got carried away at first. Since they, I've discovered that encapsulating functionality is far more useful, even if that means you have a few handles and pointers to maintain. I have a specific class that I've done both ways; the latter is far more elegant and easier to understand/debug/maintain.
modified on Sunday, April 11, 2010 8:02 PM
-
There are two ways of dealing with pointer members: Default Constructor e.g. initialize to NULL or allocate memory Destructor free memory if allocated and the class "owns" the memory Copy Constructor & Assignment Operator Handle them correctly - e.g. free the memory allocated it is good practice to use one class per unmanaged resource.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server.peterchen wrote:
it is good practice to use one class per unmanaged resource.
Unmanaged? Managing them is the whole point of C++. I think you must be a C# programmer who lost his way. ;P
You measure democracy by the freedom it gives its dissidents, not the freedom it gives its assimilated conformists.
-
peterchen wrote:
it is good practice to use one class per unmanaged resource.
Unmanaged? Managing them is the whole point of C++. I think you must be a C# programmer who lost his way. ;P
You measure democracy by the freedom it gives its dissidents, not the freedom it gives its assimilated conformists.
Thanks PtereChen, Joe and Tim for the inputs
-
Suppose a class in C++ has a pointer in it.
class
{
int*x;
}Then what all precautions we need to take regarding handling the pointer?
There is no unique answer, since it mostly depend on the semantics your class intended to be used and on the semantic of the resource (memory is a particular cas of resource, but having an
HANDLE
instead of anint*
doesn't change the nature of your question) is planned to be represented. The first thing to decide is what should happen when an instance of your class is assigned to another. Should both the classes refer to the same resource (that is: whatever modification required from both will act on the same object) or should them refer to different resources (that is: you need shallow or deep copy)? Or should one instance represent one resource, hence no copy/assignment can be done and your classes must always pass by reference?) The second thing to decide is the kind of "ownership" your class has on the resource: Does it own it (has the right to destroy it?) Is it an exclusive owner? Can it pass the ownership to somebody else? Should it share the ownership with other copies? The following table may help:no copy
shallow
deep
no ownership
use dumb pointers and disable copy and assing
use dumb pointer and don't care
NO SENSE
exclusive
delete on destruction, disable copy/assign
NO SENSE
implement copy and assign to create resource copies
pass-through
NO SENSE
use auto_ptr or implement equivalent semantic (transef the pointer to the copy and make the original pointer null)
NO SENSE
sharing
NO SENSE
use reference counting or a reference counting capable pointer (like shared_ptr)
NO SENSE
A third thing to decide is how your class acquire the resource: does it create it? Does it get it from a manages? is it created outside and passed to be handled? As you see, there are many choices, some optimal in certain cases, some optimal in other.
2 bugs found. > recompile ... 65534 bugs found. :doh:
-
peterchen wrote:
it is good practice to use one class per unmanaged resource.
Since when? I know it sounds good in theory and even I got carried away at first. Since they, I've discovered that encapsulating functionality is far more useful, even if that means you have a few handles and pointers to maintain. I have a specific class that I've done both ways; the latter is far more elegant and easier to understand/debug/maintain.
modified on Sunday, April 11, 2010 8:02 PM
Maybe I need to clarify: It is not fun to have multiple unmanaged resources as members of a single class. Reasons: First, writing the Constructors sucks. When allocating multiple resources in a single constructor, you have to deal with cleanup of a partially constructed class. (This can be leveraged by some code layout - initializing all to NULL handles before allocating everything, and a separate cleanup function that is called on construciton failure and in the DTor.) Second, you are encapsulating at the wrong level. When one class holds two file handles you are not only replicating code within the class. The bnext time you write a class holding a file handle, you will again have to implement/block the Default + Copy CTor, DTor and Assignment Operator for a properly behaving class. In Practice: I wrote "good practice", not "mandatory" or "the only way to avoid ridicule". I understand that each and every rule puts pressure on the final code. All code can ignore some pressure, good code uses the same constructs to deal with different types of pressure, but at some point the requirements will fight against each other - you can't always satisfy all of them perfectly. We only have cures, not panaceas. For a large majority of my "need to manage some resource" needs I use CHandleRefT[^] - it isn't perfect, but it works well. The fundamental deviation from OO best practices is to wrap only the resource, not the operations. This weakens encapsulation, but immensely strengthens adoption: supporting a new type of resource is just a few lines without member-to-API forwarding, and the "managed" resource can be used transparently with most native code.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server. -
Maybe I need to clarify: It is not fun to have multiple unmanaged resources as members of a single class. Reasons: First, writing the Constructors sucks. When allocating multiple resources in a single constructor, you have to deal with cleanup of a partially constructed class. (This can be leveraged by some code layout - initializing all to NULL handles before allocating everything, and a separate cleanup function that is called on construciton failure and in the DTor.) Second, you are encapsulating at the wrong level. When one class holds two file handles you are not only replicating code within the class. The bnext time you write a class holding a file handle, you will again have to implement/block the Default + Copy CTor, DTor and Assignment Operator for a properly behaving class. In Practice: I wrote "good practice", not "mandatory" or "the only way to avoid ridicule". I understand that each and every rule puts pressure on the final code. All code can ignore some pressure, good code uses the same constructs to deal with different types of pressure, but at some point the requirements will fight against each other - you can't always satisfy all of them perfectly. We only have cures, not panaceas. For a large majority of my "need to manage some resource" needs I use CHandleRefT[^] - it isn't perfect, but it works well. The fundamental deviation from OO best practices is to wrap only the resource, not the operations. This weakens encapsulation, but immensely strengthens adoption: supporting a new type of resource is just a few lines without member-to-API forwarding, and the "managed" resource can be used transparently with most native code.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server.peterchen wrote:
The bnext time you write a class holding a file handle, you will again have to implement/block the Default + Copy CTor, DTor and Assignment Operator for a properly behaving class.
If you choose to have copy constructors and assignment operators, you still have to write them with a class full of encapsulated objects. The alternative is to block copy constructors and assignment operators, which is quite easy. I have quite a few classes where I do that. (For the record, I've encapsulated a file handle and synchronization objects, though I don't always use them for various reasons; I make a decision on a case-by-case basis, based on what is best for that class, not on any rules.)
peterchen wrote:
you have to deal with cleanup of a partially constructed class.
I can't remember the last time I even worried about that; I just write my code such that it's irrelevant AND so that a class always constructs. (I don't do this in C#, but I accept slow and bloated in C#, but not in C++.)
-
peterchen wrote:
The bnext time you write a class holding a file handle, you will again have to implement/block the Default + Copy CTor, DTor and Assignment Operator for a properly behaving class.
If you choose to have copy constructors and assignment operators, you still have to write them with a class full of encapsulated objects. The alternative is to block copy constructors and assignment operators, which is quite easy. I have quite a few classes where I do that. (For the record, I've encapsulated a file handle and synchronization objects, though I don't always use them for various reasons; I make a decision on a case-by-case basis, based on what is best for that class, not on any rules.)
peterchen wrote:
you have to deal with cleanup of a partially constructed class.
I can't remember the last time I even worried about that; I just write my code such that it's irrelevant AND so that a class always constructs. (I don't do this in C#, but I accept slow and bloated in C#, but not in C++.)
Joe Woodbury wrote:
I make a decision on a case-by-case basis, based on what is best for that class
That fits my bill of the "good" in "good practice". Sometimes the pieces come together, sometimes they don't. I see "good practice" ostly as guidance when you don't know how to tell what's "best for the class". Do you roll dice? ;)
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server. -
peterchen wrote:
it is good practice to use one class per unmanaged resource.
Unmanaged? Managing them is the whole point of C++. I think you must be a C# programmer who lost his way. ;P
You measure democracy by the freedom it gives its dissidents, not the freedom it gives its assimilated conformists.
You prefer the term "raw"? :rolleyes: I am not writing C++ because I enjoyx managing resources. When I add a member, I think of the member, not it's contents. a
int *
doesn't clean up after itself, ascoped_ptr<int>
does. We could call them "potty trained", too.Tim Craig wrote:
I think you must be a C# programmer who lost his way
You, OTOH must be a C++ programmer who thinks harder is better.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server. -
You prefer the term "raw"? :rolleyes: I am not writing C++ because I enjoyx managing resources. When I add a member, I think of the member, not it's contents. a
int *
doesn't clean up after itself, ascoped_ptr<int>
does. We could call them "potty trained", too.Tim Craig wrote:
I think you must be a C# programmer who lost his way
You, OTOH must be a C++ programmer who thinks harder is better.
Agh! Reality! My Archnemesis![^]
| FoldWithUs! | sighist | µLaunch - program launcher for server core and hyper-v server.peterchen wrote:
You prefer the term "raw"?
I don't need any qualifiers but "managed" seems to be how Microsoft touts all the .NET BS.
peterchen wrote:
You, OTOH must be a C++ programmer who thinks harder is better.
I'm a C++ programmer who doesn't think C# brings anything worthwhile to the party. Just another of Microsoft's little proprietary ploys. Oh, look what Sun did with Java, I bet we can do that, too. ;P
You measure democracy by the freedom it gives its dissidents, not the freedom it gives its assimilated conformists.