I’m trying to understand the following (Lets pretend MyStorageClass is huge) :
class MyStorageClass
{
public:
string x;
string y;
string z;
};
class storage
{
public:
storage();
~storage()
{
vector<MyStorageClass *>::iterator it = myVec.begin(); it != myVec.end(); it++)
{
delete *it;
}
vector<MyStorageClass*> getItems()
{
for(int i = 0; i < 10; ++i)
{
v.push_back(new MyStorageClass());
}
return v;
}
private:
vector<MyStorageClass*> v;
};
main()
{
storage s;
vector<MyStorageClass*> vm = s.getItems();
}
From my understading, when s returns the vector and is assigned to vm this is done as a copy (by value). So if s went out of scope and calls it destructor, vm has its own copy and its structure is not affected. However, passing by value is not efficient. So, if you change it to pass by reference:
vector<MyStorageClass*>& getItems()
{
for(int i = 0; i < 10; ++i)
{
v.push_back(new MyStorageClass());
}
return v;
}
You pass the memory location of v (in class Storage). But you still assign a copy of it using the = operator to the vector vm in the Main class. So, vm is independent of v, and if Storage destructor is called vm unaffected.
Finally, if getItems returned a reference and in main you had the following:
main()
{
storage s;
vector<MyStorageClass*> &vm = s.getItems();
}
Now, vm holds the address of v. So it is affected by the Storage destructor.
Question: Is what I’ve stated above true?
Yes, you have understood this correctly. Now, if you want to take it to the next level, start by finding reasons why this is bad:
s-object is destroyed, thereby breaking the invariant that references are always valid.A better solution would be for
storageto expose methodsbeginandendthat return the corresponding iterators froms. Alternatively, you can use the Visitor-pattern for algorithms that need to operate ons.Also, in your case it seems like the vector
sis supposed to own the objects it contains. That would be a good indicator for use ofboost::ptr_vector.