当实现插入函数时,一般pair<iterator,bool>
返回的是stl库我正在实现类似stl的类。我可以在对中返回一个迭代器作为局部变量,即
itartor it;//init it
return pair<iterator,bool>(it,true);
或者我应该动态分配迭代器,即:
itartor it = new iterator;
return pair<iterator,bool>(*it,true);
按值返回迭代器。迭代器被设计为轻量级和可复制的。
You should use the first option. There is no reason whatsoever for the second, since you are dereferencing the pointer anyway. And leaking memory:
iterator it = new iterator;
return pair<iterator,bool>(*it,true);
^ dereference here -> memory leak.
Standard library iterators are designed to be passed by value. You should make sure your iterators are cheap to copy, and avoid all dynamic memory management pitfalls.
除非您知道自己在做什么(并且您能够正确处理它),否则永远不要返回动态分配的内容。因此,选择第一个。
鉴于您甚至无法在此处返回指针,这将不起作用(在您的代码示例中,您仍然会创建已分配对象/内存的副本)。