return object member best practice

Java programmer overwhelmed with vast array of choices in C++

I have 3 classes:
Surface
Vector3D
Triangle

The Triangle class will include a getNormal method, which will be called from within Surface. I'd like the getNormal method to return a Vector3D obj.

Confusion:
1. Do I simply return by obj value? (If yes, what if the Vector3D class was really complex with hundreds of members-it's not of course)?

2. If instead I return an instantiated (new) object by address, do I delete it later in Surface?

I do realize I could probably use some type of smart/shared pointer solution, but I'd really like to understand this better.
Return by value. Vector3D sounds like it's just 3 floats.
Last edited on
rocketboy9000

Thanks, but what if the Vector3D was a very complex class?
Check sizeof(Vector3D). If it's bigger than 16 bytes or so, return a dynamic object, unless you immediately assign it to something.
Last edited on
Thanks that helps. Though I am curious how you came up with 16 bytes.

Instead of dynamic obj, could I return a const reference?
Thanks
Well, 16 bytes is the combined size of 4 general purpose registers in the x86 architcture. I suspect higher than that will make it hard for the computer to pass it back.
I suppose you could return a const reference, but then you'd have to make sure you stored the data somewhere else before calling the function again.
I'm still confused about how best to set up methods that handle objects (>16 bytes); it's more of a best practices thing with me rather than getting it to work.

For example, comparing these methods:

1. update object but don't return anything:

void updateObj( MyObj & obj){
// do some stuff to obj
}

2. update object and then return it:

MyObj & updateObj( MyObj & obj){
// do some stuff to obj
return obj;
}


The 2nd case, returning the obj ref, somehow feels more familiar from Java, but seems unnecessary
There's no difference except that you can "reuse" the object in the same expression in the form:
updateObj(obj).doSomeMoreStuff();
Whether that is desirable, you'll have to decide for yourself.

In most cases, you should return by value (instead of returning a smart pointer). With (N)RVO, no copy of your object is created, as long as you keep it simple (that means: no multiple return paths returning different objects and no exceptions).
While RVO is not a mandatory optimization, all modern (and most not so modern) compilers will do it.
However, if it is extremely costly to copy your object, you might want create the object dynamically and return a smart pointer anyway as to not take the risk that some compiler will fail to apply RVO.
Topic archived. No new replies allowed.