0

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.

3
  • 1
    The issue is not related to Visual C++, hence I removed that tag. You're returning a reference to a local variable. The issue has been described in many questions such as stackoverflow.com/q/4643713 and stackoverflow.com/q/2744264 Commented Apr 27, 2015 at 19:23
  • 1
    Oops, I wanted to say "The issue is not specific to Visual C++". Commented Apr 27, 2015 at 19:29
  • Thanks for the indication. Having a hard time with pointers and references. Commented Apr 27, 2015 at 21:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes indeed. But unfortunately I am stuck to using the method as I posted since its an assignment... I kind of sorted it out by using a ' static Mapa temp'
If I were in your position, I would bring this up with your instructor. Your solution absolutely should not have to be to use a statically allocated Mapa object (such that it isn't destructed on function exit).
Yes. Will do since it also doesn't make much sense to me having to use such a solution... Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.