Sharing data in C++ object

Status
Not open for further replies.

jmmv

Ars Scholae Palatinae
970
Hi all

I'm going to write several classes that manage some kinds of data. There will be some class methods that will need to receive some objects of other classes, and I'm looking for the "best" method to share data between objects.

C++ has pointers and references. But I also see the shared data (soft/deep copies) functionality that uses QT toolkit. I find the shared data solution cleaner that others and this feels like Java objects; this way you can avoid pointer syntax and work with simple objects everywhere...

But... which one you see better to use?

Thanks!
 

Feshy

Ars Tribunus Militum
2,777
C++ has pointers and references. But I also see the shared data (soft/deep copies) functionality that uses QT toolkit.

Use pointers. It's a lot less hassle to use -> instead of . as opposed to creating copy constructors, assignment operators, etc. for each class. Even if you have to create these anyway, pointer de-referencing is MUCH faster than any deep copy will be.

Of course, if you really want to avoid pointers, just use references. Just don't return any references to local variables. Your compiler will probably yell at you if you do, anyway (though -- it WILL let you compile, usually... it'll just give you a warning.)

Heh. You're the second java programer today I've heard try to avoid using pointers. . . ;)
 

jmmv

Ars Scholae Palatinae
970
I'm doing things like this currently (with pointers):

Vector* AClass::some_function()
{
Vector* newvect = new Vector();

// Do some work here on the new vector

return newvect;
}

The object won't be destroyed when exiting the function, and this way I can pass objects really fast. Imagine passing by value a complete Vector (a class of mine), or an array... Doing a deep copy would be too time consuming.

This is why I though on qt style of doing this: soft copies and deep copies. You keep several objects that share the same data:

Vector v1;
// add some elements to v1
Vector v2 = v1;

This way, we have two different objects, v1 and v2, who internally point to the same data. Suppose we want a deep copy:

Vector v2 = v1.copy();

I still think that doing this is good, specially to avoid pointers in some cases which may be confusing for a newbie.


Now let's see a problem I encountered today when coding a class. It's called Person, and holds information on a person, like his name and email. When creating a Person object, I'm using pointers to pass data (to avoid deep copies):

Person* p = new Person(new String("My name"), new String("My email"));

This seems a bit confusing. Using the soft copy method, I would do:

Person* p = new Person("My name", "My email");

And let the code convert those strings to String objects and then pass them to the function, using soft copies. So... what do you think? Do you like this method of handling data? Or you prefer pointers?
 
Status
Not open for further replies.