C++ pointers, references, and function return values...

Started by
4 comments, last by Krohm 10 years, 12 months ago

I feel like I should understand this stuff by now... =/

Anyway, lets say I have a class:


class someClass
{
private:
    std::vector<Thing> myVector;

public:
    std::vector<Thing>& getThings();  //simply returns myVector
};

Now, lets say that I have another class which contains an instance of someClass. It has a method whose goal it is to get myVector, iterate through it and pull out some subset of the Things contained in it based on some criteria. It wants to take that subset and put references (preferably) to those Things in a new vector which it will, itself, control. This was my attempt at that (minus a lot of the details), and it definitely isn't storing references:


std::vector<Thing> otherVector; //Assume these are private data members in the class               
someClass myClass;              //HigherClass

void HigherClass::doesSomeThings()
{
    std::vector<Thing> &tempVector = myClass.getThings()
    //tempVector should be the same as myVector in myClass, yes?  Like tempVector is
    //another name for myVector?

    for(unsigned int i = 0; i < tempVector.size(); i++)
    {
        if(***some random condition is met***)
        {
            Thing &myThing = tempVector;
            //again, myThing should now be an alternate name for the Thing contained at
            //tempVector, no?
            otherVector.push_back(myThing);
        }
    }
}

So... where am I going wrong?

EDIT: Fixed Formatting

EDIT again: AAAARRGGGHH apparently you just can't store references in a container like this... which makes perfect sense for very obvious reasons and I'm just an idiot. Someone tell me that my logic at least is correct if this code was for some mythical language that allowed references to be stored in containers. :)

I'm working on a game! It's called "Spellbook Tactics". I'd love it if you checked it out, offered some feedback, etc. I am very excited about my progress thus far and confident about future progress as well!

http://infinityelephant.wordpress.com

Advertisement

Yeah, you store a reference in a pointer.

Instead of


Thing &myThing = tempVector;

you want


Thing* myThingPointer = &tempVector;


A pointer stores a memory address. A reference is a memory address. This means myThingPointer will point to whatever is at the memory addres that is tempVector currrently. Becareful: If the vector reconfigures itself, myThingPointer might not point to what you think it is anymore. It will still be pointing at the same address, but the contents of that address won't be the same. It could be anything.

AAAARRGGGHH apparently you just can't store references in a container like this...


Yes, you can, all you need to do is declare that the vector is suppose to store pointers, like this:


std::vector<Thing*>    myVector;
 

Take note of the asterisk. This will store an array of pointers for "Thing" into otherVector. The way you have it set up right now, otherVector is in fact storing an array of "Thing" objects themselves, rather than references to them.

Give reference (or pointer) to object stored on array is usually a bad idea.

In your case your class can be deleted and destroy all the object contained in the array. All the object that have taken reference to there object will have pointer to destroed memory and are likely to crash.

Another problem can araise if you are more object to the original array.

If the array reach it's capacity will reallocate the memory and move all the objects. Again object that have taken the reference will point to dirt memory.

Even if you remove an object from the original array you will have problem.

When you remove an object from a vector the remaining object on the right are shifted to occupy the remaining hole. In this case if you have given a pointer to and objected that is shifted the pointer now will point to the wrong object or to dirt memory.

Your idea will work only if you never touch the array once you give pointer around.

Another aproach is to store pointer.


class someClass
{
private:
  std::vector<Thing*> myVector;

public:
  std::vector<Thing*>& getThings(); //simply returns myVector
}; 

But this case is even worse.. I can give the pointer around but who is the owner of the pointer? Who must delete the object once is used?


class someClass
{
private:
   std::vector<std::auto_ptr<Thing> > myVector;

public:
   std::vector<std::auto_ptr<Thing> >& getThings(); //simply returns myVector
};
 

auto_ptr solve the problem (shared_ptr if you use the new standard). Smart pointer add refcount of object, so, the last that use the object will automatically delete it.

Is still a bad idea tu use standard smart pointer in game development cause they tend to fragment the memory, a better solution is to use boost::intrusive_ptr

http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/intrusive_ptr.html

That have some requirement on the object but it's fast and cache friendly.|

1) Putting a std::auto_ptr in a standard library container is non-kosher. If you have access to C++11 you can use std::unique_ptr instead.
2) Not all smart pointers use reference counting. In particular std::auto_ptr doesn't.

Someone tell me that my logic at least is correct if this code was for some mythical language that allowed references to be stored in containers

It would probably be correct in Java, as it does not have objects but only references-to-objects.

In C++ no, your logic is fundamentally flawed and a major misunderstanding. std::vector<Thing> is a vector containing blobs of type Thing, not a vector containing references to Thing objects. It will never, ever store objects 'by address'.

To have references, you must have Thing& somewhere. Actually, I'd look into std::reference_wrapper, which counts as a smart &. Standard references using & are a bit quirky, if memory serves, they can be initialized but not copied therefore they cannot live inside std::vector. Now, I don't know if this restriction has been lifted but I still wouldn't write std::vector<Thing&>.

Previously "Krohm"

This topic is closed to new replies.

Advertisement