473,725 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ownership style question


I've been using code such as the following, whereby I call the
constructor of a class with an object allocated on the heap. The
class is responsible for tidying up the memory.
class Base{};
class A : public Base {};
class B : public Base {};
class MyClass
{
private:

Base* m_pBase;

public:

MyClass(Base* pB):m_pBase(pB) {}

~MyClass(){dele te m_pBase;}
};
void SomeClass::Some Method()
{
//m_pMC is a member variable of type MyClass*

m_pMC = new MyClass(new A());

}

Intuitively, this seems like bad style. I feel that each object should
be responsible for the creation and deletion of objects it uses. Is
this intuition correct?

And, if so, how should I change the design? I can't do something like

void SomeClass::Some Method()
{
Base* pB = new A();

m_pMC = new MyClass(pB);

delete pB;
}

because m_pBase must be valid outside the scope of the class method.

How can I improve this design?

Thanks for any help and I hope this made sense!
Jul 22 '05 #1
4 2410
"tarmat" <ta****@btopenw orld.com> wrote in message
news:90******** *************** *********@4ax.c om...
|
| I've been using code such as the following, whereby I call the
| constructor of a class with an object allocated on the heap. The
| class is responsible for tidying up the memory.

The C++ standard library includes a smart pointer class that
was designed to express transfer of ownership: auto_ptr.

| class MyClass
| {
| private:
|
| Base* m_pBase;
|
| public:
|
| MyClass(Base* pB):m_pBase(pB) {}
|
| ~MyClass(){dele te m_pBase;}
| };
....
| How can I improve this design?

This could become:

class MyClass
{
private:
std::auto_ptr<B ase> m_pBase;

//NOTE: for safety, you want to disable these 2 default ops here:
MyClass(MyClass const&); // not implemented
void operator=(MyCla ss const&); // not implemented

public:
MyClass(std::au to_ptr<Base> pB):m_pBase(pB) {}
~MyClass() { /*auto-deleted*/ }
};
Note that there is a debate on whether std::auto_ptr parameters
should be passed by value (as above) or by reference.
The former is dangerous when a function has multiple parameters.
The latter is less explicit about the ownership transfer,
and can be cumbersome (requires the initialization of
an intermediate variable).
Regards,
Ivan
--
http://ivan.vecerina.com
Jul 22 '05 #2


Ivan Vecerina wrote:
"tarmat" <ta****@btopenw orld.com> wrote in message
news:90******** *************** *********@4ax.c om...
|
| I've been using code such as the following, whereby I call the
| constructor of a class with an object allocated on the heap. The
| class is responsible for tidying up the memory.

The C++ standard library includes a smart pointer class that
was designed to express transfer of ownership: auto_ptr.


You need to be careful with auto_ptr particularly with version 2
implementations which can leave you with dangling pointers. Version
three is supposed to reset the pointer to 0 after the transfer which
leads to better respect for the thing. You are probably better off with
something a little more robust like a shared_ptr.

Jul 22 '05 #3
"lilburne" <li******@godzi lla.com> wrote in message
news:bp******** *****@ID-179504.news.uni-berlin.de...
|
| Ivan Vecerina wrote:
| > "tarmat" <ta****@btopenw orld.com> wrote in message
| > news:90******** *************** *********@4ax.c om...
| > |
| > | I've been using code such as the following, whereby I call the
| > | constructor of a class with an object allocated on the heap. The
| > | class is responsible for tidying up the memory.
| >
| > The C++ standard library includes a smart pointer class that
| > was designed to express transfer of ownership: auto_ptr.
|
| You need to be careful with auto_ptr particularly with version 2
| implementations which can leave you with dangling pointers. Version
| three is supposed to reset the pointer to 0 after the transfer which
| leads to better respect for the thing. You are probably better off with
| something a little more robust like a shared_ptr.

But shared_ptr expresses shared ownership, where both the caller
and callee may keep using the owned object. It does not express
ownership transfer, and serves a very different purpose IMO.

Pre-standard versions of std::auto_ptr had problems, true.
But these are easy to avoid (assume that it is UB to use
an auto_ptr after it has been assigned to another instance).
And hopefully these outdated libraries are about to disappear
from developer's systems by now.

Yes, IIRC, MSVC6 still shipped with an awfully outdated
version of the standard library. But users who can't afford
updating their platform (nor purchasing the library update)
definitely should switch to the free STLport (www.stlport.org).
(at least if they care to use the standard C++ library at all).
Regards,
Ivan
Jul 22 '05 #4
Ivan Vecerina wrote:
"lilburne" <li******@godzi lla.com> wrote in message
news:bp******** *****@ID-179504.news.uni-berlin.de...
|
| Ivan Vecerina wrote:
| >
| > The C++ standard library includes a smart pointer class that
| > was designed to express transfer of ownership: auto_ptr.
|
| You need to be careful with auto_ptr particularly with version 2
| implementations which can leave you with dangling pointers. Version
| three is supposed to reset the pointer to 0 after the transfer which
| leads to better respect for the thing. You are probably better off with
| something a little more robust like a shared_ptr.

But shared_ptr expresses shared ownership, where both the caller
and callee may keep using the owned object. It does not express
ownership transfer, and serves a very different purpose IMO.

I agree that the semantics of ownership transfer is a good
reason to use auto_ptr. One that resets the pointer to 0
after transfer is a far more solid implementation.
Pre-standard versions of std::auto_ptr had problems, true.
But these are easy to avoid (assume that it is UB to use
an auto_ptr after it has been assigned to another instance).
And hopefully these outdated libraries are about to disappear
from developer's systems by now.


Personally I don't like UB that can appear to work, because
it doesn't discourages misuse. I suspect that a few will get
a nasty surprise with V3 auto_ptr's.

Jul 22 '05 #5

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

Similar topics

1
3858
by: Ryan | last post by:
We have a DTS package developed on our development PC's (SQL 7). It runs fine. When we schedule it on the server (SQL 7), it fails. We have been able to find that this is a known issue down to the use of permissions (running it uses the users permissions, scheduling it uses the servers). http://support.microsoft.com/?kbid=269074 Our Ops Support team insist that we have the full permissions to run this, but it still fails. If we log on to...
11
1881
by: Jacob | last post by:
I am trying to find the best way of documenting (in code and comments) ownership of secondary contained objects. This is my current status, and I would appreciate feedback on it: Case 1: When the secondary object is created with the object and dies with the object. Solution: Keep the secondary object as a stack variable, and
0
1379
by: Wells Fargo | last post by:
<html dir=3D"ltr"> <head> <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dwindows= -1252"> <title>New Page 1</title> </head> <body>
14
2729
by: Howard | last post by:
Hi, I recently had a problem where I decided to store objects in a vector. (Previously, I had always stored pointers in vectors). Well, naturally, when storing an object in a vector, using push_back, the object I had in hand was getting copied (twice, in fact). That led to a problem, in that my object contained a "handle" to another object, and when the object being pushed went out of scope and was destroyed, the referenced object was...
2
2225
by: Benden Ziyade | last post by:
Hello; I want to write a C program that check file ownership in /bin directory(ls, mkdir...). But I don't know how I start. I'm happy with your helping.
9
7216
by: Andrew | last post by:
Apologies for the double-post.. I'm new, just getting used to this.. and should have posted this way in the first place.. How does one go about taking ownership of a registry key using C# & .NET 2.0 *IF* one has _only_ TakeOwnership privilege? The problem is exactly as specified in MS KB Article ID: 111546 at: http://support.microsoft.com/kb/111546/EN-US/ ...except that I would like to know how to do it in C#
7
1828
by: Stephen Engle | last post by:
I am trying to allow for user account to take ownership of an Active Directory object. I have assigned the Modify Owner permission to the user on the AD object - a distribution list in this case. Using Active Directory Users and Computers, the user can take ownership of the object. But I have not been able to get the program I am working on to do so. Whenever I try to write the Security Descriptor back to the object, I get the...
0
1310
by: Stodge | last post by:
Hi folks, new to Boost Python and struggling to build a prototype at work. I thought I'd start with a conceptual question to help clarify my understanding. I already have a basic prototype working nicely but I'm having a few issues, which I may post about later. A brief functional rundown of what I'm trying to prototype. Hopefully my explanation doesn't get too confusing! I'm embedding a python module into an application; Python will...
0
188
by: Svend Jensen | last post by:
Leo wrote: A synonym will do. /Svend
0
9401
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
9257
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
9179
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
8099
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
6702
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
6011
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();...
0
4519
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...
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.