I made the following small program: (basically a class that disconnects if it is created, copied, or destroyed, and most importantly, what some of them do)
class Foo
{
public:
Foo(string name): _name(name)
{
cout << "Instance " << _name << " of Foo created!" << std::endl;
};
Foo(const Foo& other): _name(other._name)
{
cout << "Instance " << _name << " of Foo copied!" << std::endl;
};
~Foo()
{
cout << "Instance " << _name << " of Foo destroyed!" << std::endl;
}
string _name;
};
int main( int argc, char**argv)
{
Foo albert("Albert");
Foo bert("Bert");
{
vector<Foo> v1, v2;
system("PAUSE");
v1.push_back(albert);
system("PAUSE");
v2.push_back(bert);
system("PAUSE");
v1 = v2;
system("PAUSE");
}
system("PAUSE");
}
The result is as follows:
Instance Albert of class Foo created!
Instance Bert of class Foo created!
Press any key...
Instance Albert of class Foo copied!
Instance Albert of class Foo copied! // why another copy?
Instance Albert of class Foo destroyed! // and destruction?
Press any key...
Instance Bert of class Foo copied!
Instance Bert of class Foo copied!
Instance Bert of class Foo destroyed!
Press any key... // v1=v2 why did the albert instance not get destroyed?
Press any key...
Instance Bert of class A destroyed!
Instance Bert of class A destroyed!
Press any key... // there still an albert living in the void
It looks very strange. Why am I even confusing something as a reference if it is still copied? Why does v1.operator = (another) not destroy the elements it contains? This will work well with shared_ptr behavior. Can someone tell me why?
Addition
I put this in an endless loop and checked the memory usage, it does not seem to produce at least membrane leakage.
, mem , operator =, ctor, .
v1.reserve(10);
v2.reserve(10);
. push_back ( ).
, .reserve . :)
:
- V++ 2005.
- , operator =
, ,
. , .
- 2005 ! .
- , .