473,698 Members | 2,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Standard containers, polymorphic objects, and memory management.

I'm trying decide on the best way to structure the memory management in
my program.

I have a class (lets call it World), which contains a collection of
Entity objects.

Entity in turn, contains a pointer a Shape object. Shape is a pure
virtual class.

Now, I'm not sure who should "own" the allocation and deallocation of
the Shapes. It makes sense that World should own the Entity objects
directly, but it seems to complicate matters if I want the Entity
objects to delete (through auto_ptr, or on there own destructor) the
Shape *.

Also, I'd prefer (although its not a requirement) to avoid the "new"
operator for a lot of this. eg, I'd like to do something like this:

World world;
world.addEntity (Entity(new Sphere(spherePa rams)));

where you have:
void World::addEntit y(Entity &entity) {
entities.push_b ack(entity);
}

Now, if Entity deletes its shape on destruction, I need to make sure
that the Entity copy constructor uses move semantics, but I'm not sure
that's compatible with std::vector<Ent ity>. Or I need to make World
accept (and manage) Entity pointers.

I suppose I could also make it so that World manages the Shape object
life-cycle, eg "Shape &shape World::addShape (Shape *shape);".

So, any suggestions on which route I should take?

Thanks,
Daniel.

--
Daniel Pitts' Tech Blog: <http://virtualinfinity .net/wordpress/>
Jun 27 '08 #1
2 1454
I have a class (lets call it World), which contains a collection of
Entity objects. Entity in turn, contains a pointer a Shape
object. Shape is a pure virtual class.
Your description looks like this:

class Shape
{
// one or more pure virtual functions

};

class Entity
{
std::auto_ptr<S hapes_; // or shared_ptr<Shap e>
// ...

// has copy ctor & assignment op
// by either cloning or sharing the pointee.

};
class World
{
std::vector<Ent ityentities_;
// ...
};

So assuming you have a single World instance, memory management seems
to be taken care of.
Now, if Entity deletes its shape on destruction, I need to make sure
that the Entity copy constructor uses move semantics, but I'm not
sure that's compatible with std::vector<Ent ity>. Or I need to make
World accept (and manage) Entity pointers.
You can ensure that Shape has clear clone semantics or use shared_ptr
idiom to make it compatible to vector<Entity>. I would advise against
use of raw pointers.

-Amal
Jun 27 '08 #2
On Jun 3, 4:36 am, Daniel Pitts
<newsgroup.spam fil...@virtuali nfinity.netwrot e:
I'm trying decide on the best way to structure the memory
management in my program.
I have a class (lets call it World), which contains a
collection of Entity objects.
Entity in turn, contains a pointer a Shape object. Shape is a
pure virtual class.
Now, I'm not sure who should "own" the allocation and
deallocation of the Shapes. It makes sense that World should
own the Entity objects directly, but it seems to complicate
matters if I want the Entity objects to delete (through
auto_ptr, or on there own destructor) the Shape *.
Be careful with the concept of ownership. In most applications,
it doesn't really make sense to have a "world" object which owns
the entity objects, but rather the let the entity objects "own"
themselves. And do Shape objects really require destruction; do
they have a deterministic lifetime. If not, then the simplest
solution is to use a garbage collector, and not worry about it.

Otherwise, I don't think that there's any real problem in having
Entity be responsible for the lifetime of its Shape. But of
course, this will really depend on the actual semantics of the
objects in question. There is no one rule which fits all cases.
Also, I'd prefer (although its not a requirement) to avoid the
"new" operator for a lot of this.
If you're objects are polymorphic, you don't have much choice.
eg, I'd like to do something like this:
World world;
world.addEntity (Entity(new Sphere(spherePa rams)));
where you have:
void World::addEntit y(Entity &entity) {
entities.push_b ack(entity);
}
Why? Entity objects typically have identity, which means that
they don't support copy or assignment; they usually also have an
arbitrary lifetime. Both of which mean that they should
probably never be allocated other than dynamically.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #3

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

Similar topics

6
3371
by: Gandalf | last post by:
Hello. I have some questions about the standard containers. How does the standard containers behave if I do queue<Foo> myQ; queue<Foo> myQ2; .... insert into myQ... myQ = myQ2;
43
4986
by: Steven T. Hatton | last post by:
Now that I have a better grasp of the scope and capabilities of the C++ Standard Library, I understand that products such as Qt actually provide much of the same functionality through their own libraries. I'm not sure if that's a good thing or not. AFAIK, most of Qt is compatable with the Standard Library. That is, QLT can interoperate with STL, and you can convert back and forth between std::string and Qt::QString, etc. Are there any...
4
1566
by: Vincenzo Cappello | last post by:
I need a map that contain different object of the same base class like: std::map< int, base_class* > someone tell me is no correct using pointer in containers so i change to: std::map< int, std::auto_ptr< base_class > > someone tell me is no correct using auto_ptr in containers...
35
2832
by: dragoncoder | last post by:
Just a simple theoritical question to the experts. What was the rationale behind making STL containers follow copy semantics rather than reference semantics. References almost always make things easier without much of overhead. Then why not reference ? Thanks /P
21
2207
by: George Exarchakos | last post by:
Hi everyone, I'd like your help... Can we have a std::list<BASEwhere BASE be the base class of a class hierarchy? I want to add to this list objects that are inherited from BASE class but not necessarily the same... class base { int x;
2
4612
by: Arash Partow | last post by:
Hi all, I've got a question related to emulating aspects of polymorphism with CRTP. Below is a typical polymorphic class hierarchy with a definition of a "somewhat" heterogeneous container of objects. class poly_base { public: virtual int foo(int i, int j) = 0; };
7
1468
by: mscava | last post by:
Hi... Today I was trying to find the best way to handle elements in Containers. I've found 3 appraoches but all do have pros and cons... 1. std::vector<MyClass> - inefficient - you have to write assing an copy constructor - to add new element into container you do need 2 lines of code + very comfortable use of algorhitms from STL 2. std::vector<MyClass*>
14
1640
by: Remo D. | last post by:
I've read with much interest the threads on how to create data containers in C. I started thinking if simpler ADT (other than the proposed List) could be used as a starting point. What about a dynamic vector? I mean a dynamic array with no predefined size. A possible API could be: typedef struct {
3
2062
by: massysett | last post by:
Greetings, Having classes with member objects that have STL containers of objects whose definitions are incomplete results in undefined behavior. See for example: http://www.ddj.com/database/184403814#8 http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.14 I am wondering: is it okay to have member functions that return an STL
0
8604
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
9157
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
9028
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
8895
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
6518
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
4369
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...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
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
2330
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.