473,804 Members | 3,085 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copying and assigning of resource-owning objects

Say i have an object that represents or holds a resource like an open
file, a block of memory on the heap, or an openGL texture object. The
constructor acquires the resource, and the destructor releases it. I
want to implement efficient copying and assignment for this object -
the copy constructor passes on the 'handle' (file pointer, memory
pointer, or opengl texture id) to the new object, and invalidates the
old object. I guess this is how the std::auto_ptr works too. I can
come up with several ways to do this, but i'd like to see how it
usually done, since i guess this is a quite common problem and people
will undoubtedly have come up with a brilliant solution.
Possible method: Have a boolean valid flag in the object, all methods
that require the resource check this flag and report error when the
object is not valid. Destructor only releases the resource if the
object is valid. The copy constructor and assignment operator set this
flag to false in the original object and copy the handle variable
instead of initalizing their own resource. Is this The Way To Do It,
or does it have flaws?

Marijn Haverbeke
Jul 19 '05 #1
2 1833
"Marijn" <ma******@hotma il.com> wrote...
Say i have an object that represents or holds a resource like an open
file, a block of memory on the heap, or an openGL texture object. The
constructor acquires the resource, and the destructor releases it. I
want to implement efficient copying and assignment for this object -
the copy constructor passes on the 'handle' (file pointer, memory
pointer, or opengl texture id) to the new object, and invalidates the
old object. I guess this is how the std::auto_ptr works too. I can
come up with several ways to do this, but i'd like to see how it
usually done, since i guess this is a quite common problem and people
will undoubtedly have come up with a brilliant solution.
Possible method: Have a boolean valid flag in the object, all methods
that require the resource check this flag and report error when the
object is not valid. Destructor only releases the resource if the
object is valid. The copy constructor and assignment operator set this
flag to false in the original object and copy the handle variable
instead of initalizing their own resource. Is this The Way To Do It,
or does it have flaws?


The matter gets a bit more complicated when you consider the need to
have temporaries of that type or const objects of that type. You
probably need to implement some kind of reference counting scheme
for that. It's not that difficult, but it's relatively tedious (to
cover all bases, mainly).

You probably don't need a boolean flag. Keep your resources pointers
and simply set them to 0 when the resource is freed or transferred to
another object. Implement the copy constructor using a non-const
reference and let the constructed object transfer the ownership from
the object from which it's being constructed:

class MyType {
...
MyType(MyType& from) : myresource(from .myresource) {
from.resourceIs TakenBy(this);
}
void resourceIsTaken By(MyType* heir) {
myresource = 0; // any other processing? Logging?
}
};

Take a look at the implementation of different smart pointers (the
auto_ptr in your standard library, the Boost's one, whatever else
you can find on the web). Just as you've guesses, they do have all
those features: ownership and its transfer, cleaning up when dying,
some have reference counting...

Victor
Jul 19 '05 #2
Thanks for the reply!

"Victor Bazarov" <v.********@att Abi.com> wrote:
The matter gets a bit more complicated when you consider the need to
have temporaries of that type or const objects of that type. You
probably need to implement some kind of reference counting scheme
for that. It's not that difficult, but it's relatively tedious (to
cover all bases, mainly).
I can see the problem with const objects, but what issues can come up with
temporaries? (in the problem that led to this post i do not need consts, just
temporary objects - pushing stuff into std containers right away, as in
container.push_ back(TextureObj ect(45)); )
I used the reference counting thing to implement a string class (yeah i know,
i like reinventing wheels), but i was aiming for a simpler, more efficient, less
error-prone approach here. I do not need multiple objects pointing at the same
resource, so i'll just cop out and use an invalidation scheme.
You probably don't need a boolean flag. Keep your resources pointers
and simply set them to 0 when the resource is freed or transferred to
another object.
Sure. I was talking about generic resource, some of which might have identi-
fiers that could be zero, but for pointer NULL works okay.
Take a look at the implementation of different smart pointers (the
auto_ptr in your standard library, the Boost's one, whatever else
you can find on the web). Just as you've guesses, they do have all
those features: ownership and its transfer, cleaning up when dying,
some have reference counting...


Good idea, i was already imitating the std::auto_ptr behaviour, but why
imitate when you can literally copy how it is done there, ha.

Marijn

Jul 19 '05 #3

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

Similar topics

4
2981
by: Alex Vinokur | last post by:
Copying files : input to output =============================== C/C++ Performance Tests ======================= Using C/C++ Program Perfometer http://sourceforge.net/projects/cpp-perfometer http://alexvn.freeservers.com/s1/perfometer.html
0
1217
by: Yoav Berenstein | last post by:
I need to copy an EventHandler assigned to one resource, to another (runtime generated) resource. Here is the code I used : public void test(object xi_sender) { System.Windows.Forms.Menu parent = (xi_sender as System.Windows.Forms.MenuItem).Parent;
0
1050
by: Wysiwyg | last post by:
Is there any way to add an embedded resource to a project without copying it to the project's directory? I have shared resources and don't want each project using the images, xml files, etc. to need to be updated with the current copy before being built. I also don't want projects being built with the old copy. Thanks! Bill
1
2117
by: Terry Olsen | last post by:
Ok, now that I've got my disk imager program working, I'd like to attach a "self-extractor" to the front end of the image file and make it a self-extracting disk image executable file. The idea being that the user would double-click on the file and the disk would be created. I would like to be able to "create" the self-extracting disk image from my program. Any guidance on how to go about doing this? thanks.
3
1148
by: kiwi | last post by:
Hello: I have a DLL that must update into a server. I want to make automatic proccess that copy that dll from a directory(Ex: c:\update) to application directory (ex: c:\application). Copy file is easy, but the problem is that copying it does not get the same right access that app. directory has. How can I copy this file assigning the correct right access? (from c:\application directory)
2
8099
by: Jerad Rose | last post by:
I have a fairly simple C# console app which copies files from a network folder to a local folder. When the app resides on my local C: drive, it runs just fine. However, when the app resides on a network drive, copying the same files from the same source drive and to the same destination drive, it gives me the following exception: System.Security.SecurityException: Request for the permission of type...
31
17714
by: leonm54 | last post by:
I remember that this is a bad practice, but can not find a definitive resource that states it is bad and why. Can anyone help?
3
6401
by: IvaPopova | last post by:
Hello, Consider this use strict; use Data::Dumper; my %hash1=(a=>, b=>, c=>,);
9
4263
by: Mr John FO Evans | last post by:
Am looking at adding structures to an embedded C emulator but am wondering what the standard is for copying structures(ie structa=structb) which contain pointers to memory and which are therefore not contiguous in memory. When such structures are copied what should C do with these elements? Or should copying be illegal in this case? John
0
1160
by: =?Utf-8?B?Um9nZXI=?= | last post by:
Hello, My question is about assigning FullTrust to all the programs installed on a network shared folder called \\myserver\programfiles, for all the pcs on a network domain: I'm working on an enterprise with a network based on a windows server domain. Each time I develop and put a new program on a shared resource within \\myserver\Program Files\program_name, I follow these steps
0
9704
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
9569
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
10558
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...
0
10318
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10302
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
9130
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
7608
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
5636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2975
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.