简体   繁体   English

分配一个stl容器是否安全?

[英]is it safe to assign a stl container?

For example: 例如:

set<int> s1;
set<int> s2;
s1.insert(1);
s2.insert(2);
s1 = s2;

Is it safe? 安全吗? If so, where did the old element(and the memory they occurred) come to? 如果是这样,旧元素(以及它们发生的内存)来自哪里?

Yes it's safe to do the assignment. 是的,完成任务是安全的。 It calls the copy constructor or assignment operator and the older elements are erased in s1 and are replaced by the elements of s2 . 它调用复制构造函数或赋值运算符,旧元素在s1被擦除,并被s2的元素替换。

[Note: If there would have been any potential problem then copy constructor and assignment would have been forbidden like fstream , ofstream , ifstream .] [注意:如果存在任何潜在问题,那么复制构造函数和赋值将被禁止,如fstreamofstreamifstream

Yes. 是。 The old elements will be destroyed in the usual way and any memory freed. 旧元素将以通常的方式被销毁并释放任何内存。 (Of course as usual if you store pointers in the container it will only destroy the pointer, and won't free the thing it points to) (当然像往常一样,如果你将指针存储在容器中,它只会破坏指针,并且不会释放它所指向的东西)

Yes your examples is safe. 是的你的例子是安全的。 But note: You don't assign s2 to s1, you copy s2 to s1. 但请注意:您没有将s2分配给s1,而是将s2复制到s1。 For further information see this: set::operator= 有关详细信息,请参阅: set :: operator =

The assignment is safe. 任务是安全的。

The assignment operator will destroy the objects originally contained in s1 by calling their destructor (a trivial no-op for the int in your example). 赋值运算符将通过调用它们的析构函数来破坏最初包含在s1中的对象(在您的示例中,int是一个简单的无操作)。 Whether the set frees the memory as well, or retains it as uninitialized memory for use by subsequently added elements, is up to the implementation. 该集合是否释放内存,或者将其保留为未初始化的内存以供后续添加的元素使用,取决于实现。

The new objects in s1 will be copied from those in s2, which might take considerable time. s1中的新对象将从s2中的新对象复制,这可能需要相当长的时间。 In case you don't want to keep s2 around after the assignment, better approaches might be to swap the two containers or to use the C++11 move assignment. 如果您不想在分配后保留s2,更好的方法可能是交换两个容器或使用C ++ 11移动分配。

std::swap(s1, s2);  // Backwards-compatible swap
s1 = std::move(s2); // C++11 rvalue move assignment

Both of these will most likely just swap a single pointer, leaving the content you want to keep in s1 and the rest in s2, to be cleared when s2 goes out of scope. 这两个都很可能只是交换一个指针,当s2超出范围时,将要保留在s1中的内容和其余在s2中的内容清除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM