hadroque
hadroque

Reputation: 15

Why can't I return this vector of vectors?

I have a class that declares a vector of vectors of type char as the following and contains a method to read half of it and return the resulting vector.

class Mapa 
{
private:
    vector<vector<char> > vec;

public:
    //Constructor
    Mapa():vec(0,vector<char>(0)){};

    Mapa(int row, int col):vec(row, vector<char>(col)){};
    virtual ~Mapa(){};
     }

const Mapa& just_Half()
    {

        Mapa temp(vec.size(),vec[0].size());
        int a = vec.size()*vec[0].size()/2;
        for (int i = 0; i < vec.size() && a>0; i++, a--)
            for (int j = 0; j < vec[i].size() && a>0; j++, a--){
                temp.vec[i][j]=vec[i][j];
            }
        return temp;

    }

in main I do:

Mapa Mapa1(3, 10);
Mapa Mapa2;
Mapa2=Mapa1.just_Half();

My question is why is Map2 just and empty vector at the end of this? Why doesn't it receive temp?

Thanks for any help.

Upvotes: 0

Views: 288

Answers (1)

huu
huu

Reputation: 7472

The issue is that your return type is a reference to a Mapa. The Mapa (named temp inside the function) you're returning is destructed when the function goes out of scope, so you're returning a destructed Mapa, which is undefined.

The solution is simple, return by value instead of by reference:

const Mapa just_Half()
{

    Mapa temp(vec.size(),vec[0].size());
    int a = vec.size()*vec[0].size()/2;
    for (int i = 0; i < vec.size() && a>0; i++, a--)
        for (int j = 0; j < vec[i].size() && a>0; j++, a--){
            temp.vec[i][j]=vec[i][j];
        }
    return temp;
}

If you're concerned that this does an unnecessary copy, don't worry. Compilers will almost always optimize that copy operation away with return value optimization.

Upvotes: 2

Related Questions