And*_*asT 5 c++ stl visual-studio-2005
我已经制作了以下小程序:(基本上是一个类,如果它被创建,复制或销毁,并且主要执行其中一些)
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");
}
Run Code Online (Sandbox Code Playgroud)
输出如下所示:
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's still an albert living in the void
Run Code Online (Sandbox Code Playgroud)
这让我非常奇怪.如果它被复制两次,为什么我甚至不愿意传递一些东西作为参考呢?为什么v1.operator =(other)不会破坏它包含的元素?它很适合shared_ptr的行为.有人可以告诉我为什么吗?
添加 我把它放在无限循环中并检查内存使用情况,它似乎至少没有产生内存泄漏.
添加 好吧,mem不是问题,因为它使用operator =而不是copy ctor,好的,谢谢.当我添加
v1.reserve(10);
v2.reserve(10);
Run Code Online (Sandbox Code Playgroud)
逻辑份数发生.没有它,它会为每一个push_back重新分配和复制整个向量,(即使对于小向量,我也发现它非常迟钝).看着这个我会考虑使用.reserve更多并优化我的赋值运算符像地狱:)
附加:摘要
如果某个东西被复制了两次,为什么我还要费心传递一些东西作为参考呢?
您应该将 STL 容器类型视为黑盒,可以根据需要经常复制您存储的对象。例如,每次调整容器大小时,所有对象都将被复制。
您的编译器的实现可能push_back()
使用临时的额外副本。在我的机器上(Mac OS X 上的 gcc),期间没有额外的副本push_back()
(根据程序的输出)。
此复制发生在 STL 代码中的某个位置,而不是在复制构造函数中(因为它使用引用)。
为什么 v1.operator=(other) 不破坏它包含的元素?
Foo::operator=
将以“bert”实例作为参数调用“albert”实例。因此,这里没有隐式的销毁和复制操作。您可能想通过为操作员提供您自己的实现来验证这一点:
Foo& operator=(const Foo& other) {
cout << "Instance " << other._name << " of Foo assigned to " << _name << "!" << std::endl;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这会在我的机器上产生以下输出:
Foo 的实例 Albert 创建了!
Foo 的实例 Bert 创建了!
Foo 的艾伯特实例复制了!
Foo 实例 Bert 复制了!
Foo 的实例 Bert 分配给 Albert!
Foo 的实例 Bert 被摧毁!
Foo 的艾伯特实例被摧毁!
Foo 的实例 Bert 被摧毁!
Foo 的艾伯特实例被摧毁!