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?