简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM