Hi all,
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
Thanks a lot!
Michael
#include <iostream>
using namespace std;
class Dummy {
public:
int n;
};
class Victim {
private:
Dummy *d;
public:
Victim() {
d = new Dummy();
d->n = 23;
}
Dummy* getDummy() {
return d;
}
};
int main(int argc, char **argv) {
Victim *v = new Victim();
Dummy *d = v->getDummy();
cout << d->n << endl;
delete d;
cout << d->n << endl;
return 0;
}
// EOF
Output:
23
0 22 1951
Michael Pradel wrote:
Hi all,
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
You could use boost::shared_p tr with a nop deleter.
void noop() {}
shared_ptr<Tget T() const { return shared_ptr<T>(t , bind(&noop)); }
However, I imagine this could cause problems if you where to finish
using all the shared_ptrs that have deleters before this returned one
went out of scope. Unfortunately shared_ptr is the only one that
appears to let you override the deleter.
On Jan 26, 8:51 am, Michael Pradel <mich...@binaer varianz.dewrote :
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: >
int main(int argc, char **argv) {
Victim *v = new Victim();
Dummy *d = v->getDummy();
cout << d->n << endl;
delete d;
cout << d->n << endl;
return 0;}// EOF
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
By simply observing a simple rule: the code responsible for allocating
an object is also solely responsible for that object's deallocation. In
this case, main() did not explicitly (or directly) allocate the Dummy
object, "d", so main() should not be deleting "d".
On the other hand, main() did allocate "v', so main() should delete v
before it exits. Deleting v should cause v to delete d (since v was
responsible for allocating d in the first place). The fact that the
Victim class does not deallocate its d member should be considered a
bug in the program.
So by observing this simple convention regarding object deallocation,
everyone ends up minding their own affairs and no one interferes with
the affairs of anyone else. As a practical matter, though, a C++
program should avoid explicit new and delete calls - and instead rely
on shared_ptr's or auto_ptr's to manage object lifetimes on its behalf.
Greg
Michael Pradel <mi*****@binaer varianz.dewrote :
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
By documenting who is responsible for the object's deletion. The way I
do that is by returning a reference when I don't want them to delete the
object and a pointer when I do. (Yes they could still delete the object,
but in the documentation I've told them not to do it, so they either
know not to, or they are ignorant.)
Is returning a clone of it the only possibility?
That or simply not giving them access to it.
In article <ep**********@a ioe.org>, Noah Roberts <us**@example.n et>
wrote:
Michael Pradel wrote:
Hi all,
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
You could use boost::shared_p tr with a nop deleter.
void noop() {}
shared_ptr<Tget T() const { return shared_ptr<T>(t , bind(&noop)); }
delete &*getT();
On Jan 26, 1:42 pm, "Daniel T." <danie...@earth link.netwrote:
In article <epdc6p$is...@a ioe.org>, Noah Roberts <u...@example.n et>
wrote:
Michael Pradel wrote:
Hi all,
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
You could use boost::shared_p tr with a nop deleter.
void noop() {}
shared_ptr<Tget T() const { return shared_ptr<T>(t , bind(&noop)); }delete &*getT();
What about returning a const ptr. Shouldn't that prevent the deletion?
May be of limited usefullness, but it is one way of solving the
problem. You could also make the destructor private and control who can
delete the object.
By simply observing a simple rule: the code responsible for allocating
an object is also solely responsible for that object's deallocation.
That's a good solution for most of the cases, but e.g. using the Factory
Method design pattern it doesn't make sense. Here one class is only
responsible for creating the object while another will use it and knowns
when to delete it.
Product* Factory::create (ProductID id) {
if (id == A) return new ProductA;
// ...
}
That's one of the examples why I am looking for a general way to
distinguish the case where the using class may delete the returned
object and the case where it shouldn't.
Michael
What about returning a const ptr. Shouldn't that prevent the deletion?
You mean the following?
const Dummy* getDummy() {
return d;
}
That doesn't work. The deletion works nevertheless.
Michael
JLS wrote:
>
On Jan 26, 1:42 pm, "Daniel T." <danie...@earth link.netwrote:
>In article <epdc6p$is...@a ioe.org>, Noah Roberts <u...@example.n et> wrote:
>>Michael Pradel wrote: Hi all, I just returned to C++ after programming in other languages, and find myself a bit puzzled about the following issue: (see attached code). How can I avoid the deletion of an object that is returned by a method? Is returning a clone of it the only possibility? That would use a lot of memory in case of larger objects. You could use boost::shared_p tr with a nop deleter. void noop() {} shared_ptr<Tg etT() const { return shared_ptr<T>(t , bind(&noop)); }delete &*getT();
What about returning a const ptr. Shouldn't that prevent the deletion?
Nope.
--
Clark S. Cox III cl*******@gmail .com
Noah Roberts wrote:
Michael Pradel wrote:
>Hi all,
I just returned to C++ after programming in other languages, and find myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method? Is returning a clone of it the only possibility? That would use a lot of memory in case of larger objects.
You could use boost::shared_p tr with a nop deleter.
void noop() {}
shared_ptr<Tget T() const { return shared_ptr<T>(t , bind(&noop)); }
void noop(void*){}
return shared_ptr<T>(t , noop);
However, I imagine this could cause problems if you where to finish
using all the shared_ptrs that have deleters before this returned one
went out of scope. Unfortunately shared_ptr is the only one that
appears to let you override the deleter.
Not if the code is using shared_ptr correctly. It should create a
shared_ptr object that manages the newly created T object. Everything
that needs the T object gets a copy of that shared_ptr. But in that
case, the noop deleter is wrong: the last shared_ptr object should
delete the object.
The real problem is that you can't dictate application-level policies
with low-level classes. If somebody wants to go out of their way to
delete something that they're not supposed to delete, there's not much
you can do about it. So don't bother.
--
-- Pete
Roundhouse Consulting, Ltd. ( www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." ( www.petebecker.com/tr1book) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: John Bailo |
last post by:
The c# *return* statement has been bothering me the past few months.
I don't like the fact that you can have different code paths in a method
and have multiple return statements. To me, it would be more orthogonal
if a method could only have one return statement.
--
|
by: John Black |
last post by:
Hi,
I wonder what is the difference between ending the main() with and
without exit(0)?
My code is like this flow,
class ClassA{
ClassB* cb;
int toExit();
|
by: PengYu.UT |
last post by:
Hi,
Suppose I have the following class declaration with a pointer as the
argument. And suppose I "new" an array "lengths" as the argument
"edge_lengths". Now, the polygon object is valid. Unfortunately, it
becomes invalid after I delete "lengths" array be mistake.
My question is that using object, the object's(an polygon object in
this case) internal states are encapsulated. They should not be affect
by anything operations unless the...
|
by: Jack Addington |
last post by:
I have a 3rd party object that fires an itemchanged event when someone edits
some data on a form. This event has a custom eventArgs that has a field
called ActionCode. In the code of the event, if you set this ActionCode to
various values the control will respond in various ways (reject, reject
change field, accept, etc). I am trying to understand exactly how that
works as I am trying to extend the control and add more processing s...
|
by: dcassar |
last post by:
I have had a lively discussion with some coworkers and decided to get
some general feedback on an issue that I could find very little
guidance on. Why is it considered bad practice to define a public
member with a return type that is derived from System.Exception? I
understand the importance of having clean, concise code that follows
widely-accepted patterns and practices, but in this case, I find it
hard to blindly follow a standard...
| |
by: pooba53 |
last post by:
I am working with VB .NET 2003.
Let's say my main form is called Form1.
I have to launch a new form (Form2) that gathers input from the user.
How can I pass variable information back to Form1 before calling the
Me.close() on Form2?
-Stumped
|
by: Sergio Montero |
last post by:
I have a MustInherits Base class that implements a custom IDataLayer
interfase. IDataLayer expose CRUD methods. Base class constructor requires
two parameters:
ConnectionString
TableName
Another assembly, sharing the root namespace, contains a set of Custom
attributes used to validate properties values, just like the Validation
Application Block.
|
by: klenwell |
last post by:
Another request for comments here.
I'd like to accomplish something like the scheme outlined at this page
here:
http://tinyurl.com/3dtcdr
In a nutshell, the form uses javascript to hash (md5) the password
field using a random one-time salt (nonce) -- generated by php and
pasted in the form -- that is then posted with the hashed password
|
by: =?Utf-8?B?SmVhbi1GcmFuY29pcyBCcmV0b24=?= |
last post by:
"siddharthkhare@hotmail.com" wrote:
The context is important in this kind of design concern : I assume there's a
lot of user and that application will evolve to add richer functionality.
My first concern would be to separate the business logic code from data
contener : the new code would look like that :
LineItemBusinessComponent.Delete(LineItemBusinessEntity)
Exposing CRUD component isn't the best thing to do because your presentation...
|
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,...
|
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...
| |
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,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |