473,836 Members | 2,122 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object ownership and memory management

I have three classes in my example. Foo, FooRepository and FooImpl.
Foo is a lightweight wrapper around FooImpl. The idea is that Foo
can be used to pass elements by value from FooRepository to the
client code.

One option would be to use shared_ptr, but this seems like overkill
for my particular situation. The client will not be storing or
copying the Foo objects, so I have chosen to implement Foo in the
following way:

class Foo {
public:
Foo(FooImpl* impl) : pimpl_(impl) {}
//A few functions follow that simply forward requests
//...
private:
auto_ptr<FooImp l> pimpl_;
};

FooRepository returns Foo objects by value. The signature is:

class FooRepository {
public:
Foo getFoo();
};

And the client code does the following:

Foo foo = aFooRepository. getFoo();

The idea is that the foo object created here has ownership of the
FooImpl and when it goes out of scope, the FooImpl is automatically
deleted. Resource leaks are also handled in case the return value
is ignored.

This works great on Forte compilers, but fails on GCC with the
error message:

Foo.cpp: In function `int main(int, char**)':
Foo.cpp:25: error: no matching function for call to `Foo::
Foo(Foo)'
Foo.h:16: error: candidates are:
Foo::Foo(Foo&)
Foo.h:18: error:
Foo::Foo(FooImp l*)

It appears that the presence of the auto_ptr in the Foo class
prevents the compiler from generating the copy constructor taking a
const-ref parameter, and the client code matching the function call
properly.

The error message makes no sense to me because the copy constructor
cannot be written to take a parameter by value.

What is the best way to handle this situation? Am I missing
something obvious? I realize that the tradeoff I made here was to
simplify memory management but gave up the possibility of storing
my Foo objects inside containers. Is there a standard pattern for
this type of object management?

Sep 26 '05 #1
3 2330
In article <11************ **********@g44g 2000cwa.googleg roups.com>,
ja************* @gmail.com wrote:
class Foo {
public:
Foo(FooImpl* impl) : pimpl_(impl) {}
//A few functions follow that simply forward requests
//...
private:
auto_ptr<FooImp l> pimpl_;
};

FooRepository returns Foo objects by value. The signature is:

class FooRepository {
public:
Foo getFoo();
};

And the client code does the following:

Foo foo = aFooRepository. getFoo();

The idea is that the foo object created here has ownership of the
FooImpl and when it goes out of scope, the FooImpl is automatically
deleted. Resource leaks are also handled in case the return value
is ignored.

This works great on Forte compilers, but fails on GCC with the
error message:

Foo.cpp: In function `int main(int, char**)':
Foo.cpp:25: error: no matching function for call to `Foo::
Foo(Foo)'
Foo.h:16: error: candidates are:
Foo::Foo(Foo&)
Foo.h:18: error:
Foo::Foo(FooImp l*)

It appears that the presence of the auto_ptr in the Foo class
prevents the compiler from generating the copy constructor taking a
const-ref parameter, and the client code matching the function call
properly.
The compiler is automatically generating this copy constructor:

Foo(Foo&);
The error message makes no sense to me because the copy constructor
cannot be written to take a parameter by value.
The compiler means that given the expression Foo(Foo(...)), there's no
matching constructor since it can't bind the rvalue Foo() to the
parameter in Foo(Foo&).
What is the best way to handle this situation? Am I missing
something obvious? I realize that the tradeoff I made here was to
simplify memory management but gave up the possibility of storing
my Foo objects inside containers. Is there a standard pattern for
this type of object management?


There will be a standard pattern in C++0X. ;-)

struct FooImpl {};

class FooRepository;

class Foo {
private:
friend class FooRepository;
explicit Foo(FooImpl* impl) : pimpl_(impl) {}
public:
//A few functions follow that simply forward requests
//...
private:
std::unique_ptr <FooImpl> pimpl_;
};

class FooRepository {
public:
static Foo getFoo() {return Foo(new FooImpl);}
};

int main()
{
Foo foo = FooRepository:: getFoo();
}

But this won't work for you today. One thing you can try is this:

class Foo {
private:
friend class FooRepository;
explicit Foo(FooImpl* impl) : pimpl_(impl) {}
public:
Foo(const Foo& f) :
pimpl_(const_ca st<std::auto_pt r<FooImpl>&>(f. pimpl_)) {}
//A few functions follow that simply forward requests
//...
private:
std::auto_ptr<F ooImpl> pimpl_;
};

It is a little dangerous as you must always remember that every time you
copy from a Foo, the source is silently changed:

Foo x;
Foo y = x; // x is now non-owning

In your use case, if the client truly does not store copies of Foo
(other than from getFoo), then no harm is done since you only copy from
rvalues. However if your clients decide to start copying Foo's, things
can silently go bad. shared_ptr would be a safer but more expensive
alternative today. The unique_ptr example first shown will be cheap as
auto_ptr and safe tomorrow.

-Howard
Sep 26 '05 #2
ja************* @gmail.com wrote:
I have three classes in my example. Foo, FooRepository and FooImpl.
Foo is a lightweight wrapper around FooImpl. The idea is that Foo
can be used to pass elements by value from FooRepository to the
client code.

One option would be to use shared_ptr, but this seems like overkill
for my particular situation. The client will not be storing or
copying the Foo objects, so I have chosen to implement Foo in the
following way:

[snip]

I don't think it's overkill. Use a good smart-pointer implementation
(e.g. boost). It saves you time and stress. Why reinvent the wheel? And
even if you can't save time by this (time you save by not writing code
vs. time you need to introduce a lib), you still get more familar with a
smart-pointer lib, which is very important and a good trade-off.

Gabriel
Sep 27 '05 #3
Thanks for the prompt responses. I believe that Gabriel is correct in
retrospect. It's better to go with shared_ptr than to risk the
possibility of things going silently bad with the const_cast solution.

Sep 27 '05 #4

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

Similar topics

16
3044
by: D Witherspoon | last post by:
I am developing a Windows Forms application in VB.NET that will use .NET remoting to access the data tier classes. A very simple way I have come up with is by creating typed (.xsd) datasets. For example dsParts.xsd and including that in the data tier. I then will create a class that looks like this Public Class CPart Inherits dsParts
27
2006
by: ajay | last post by:
Why would a new of object be created without assigning it to any of variable? new A; ??? tx
5
2129
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I can get! Consider 3 classes in the following heirarchy: base / \ deriv1 deriv2 \
6
7970
by: Squeamz | last post by:
Hello, Say I create a class ("Child") that inherits from another class ("Parent"). Parent's destructor is not virtual. Is there a way I can prevent Parent's destructor from being called when a Child object goes out of scope? Specifically, I am dealing with a C library that provides a function that must be called to "destruct" a particular struct (this struct is dynamically allocated by another provided function). To avoid memory
17
2600
by: Divick | last post by:
Hi, I am designing an API and the problem that I have is more of a design issue. In my API say I have a class A and B, as shown below class A{ public: void doSomethingWithB( B * b) { //do something with b //possibly store in a list
6
2256
by: Pablo | last post by:
Hello, I am writing a windows application using C++ and BorlandBuilder 6 compiler. It is an event driven program and I need to create objects of some classes written by me. One of the classes contains a pointer to int values as a filed. In the definition (implementation) of constructor I use this pointer to create table of int values with the new operator. The number of elements of the table is provided by the user during execution of the...
62
4373
by: Laurent Deniau | last post by:
I just put the draft of my paper on the web: http://cern.ch/laurent.deniau/html/cos-oopsla07-draft.pdf I would be interested by any feedback from C programmers (with little OO knowledge) to improve the paper quality, even if I don't know yet if the paper will be accepted. It is not intended to be a manual nor an introduction to OOP. Just to mention it (not in the paper), my programming background is 10+ years of C/C++.
10
2587
by: Jess | last post by:
Hello, If I create a temporary object using a dynamically created object's pointer, then when the temporary object is destroyed, will the dynamically created object be destroyed too? My guess is that it's not destroyed, but I'm not sure. I have the following program: #include<iostream>
0
1314
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
9812
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
9657
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
10823
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
10577
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,...
1
7775
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
5642
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...
1
4443
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
2
4003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3103
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.