samedi 16 juin 2018

Returning a vector by reference

i have the following issue.

typedef std::pair<VertexT,CostT>  LocalEdgeT;
typedef std::vector<LocalEdgeT>   NeighborT;
typedef std::size_t                 VertexT;
typedef double                      CostT;

virtual const NeighborT& getNeighbors( VertexT v) const override   
    {
        std::vector<LocalEdgeT> neighbors;
        //here I'm adding elements, not important for the question
        return neighbors;
    }

I can not make the function return NeighborT without reference, because I have to use a function that's given to me from my university, that requires the reference for some reason.

But when I return it with the following call in main:

std::vector<NeighborT> test = Object.getNeighbors(arg);

It gives a segmentation fault, probably because I'm returning reference to a local variable. Any idea how I can fix it, that it still returns the vector by reference and it works with my function call in the main method? Furthermore I have to compile with c++11 standard.

Aucun commentaire:

Enregistrer un commentaire