473,387 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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<FooImpl> 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(FooImpl*)

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 2307
In article <11**********************@g44g2000cwa.googlegroups .com>,
ja*************@gmail.com wrote:
class Foo {
public:
Foo(FooImpl* impl) : pimpl_(impl) {}
//A few functions follow that simply forward requests
//...
private:
auto_ptr<FooImpl> 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(FooImpl*)

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_cast<std::auto_ptr<FooImpl>&>(f.pimpl _)) {}
//A few functions follow that simply forward requests
//...
private:
std::auto_ptr<FooImpl> 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
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...
27
by: ajay | last post by:
Why would a new of object be created without assigning it to any of variable? new A; ??? tx
5
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...
6
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...
17
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...
6
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...
62
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...
10
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...
0
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.