如果在函数内部,我将数据存储在unordered_set中,然后将指针返回到要存储的对象,这些指针在函数范围之外是否仍然有效?
例如。
int *myFunc(){
std::unordered_set<int> hashset;
//add some objects
hashset.insert(4);
hashset.insert(5);
hashset.insert(6);
int *intptr = &(*hashset.insert(4)); //try to insert an object that may already be in the set, and get a pointer to the object in the set
return intptr;
}
试图访问*intptr
另一个函数会导致错误吗?还是在unordered_set范围结束时释放unordered_set中的数据?
是的,在您的示例中,您将返回一个对象,该对象在unordered_set
调用的析构函数时即函数退出其作用域时已被破坏。
即使包含在中的元素unordered_set
是动态分配的(并且我所说的元素是指包含有效键或值的对象),当集合本身销毁时,它们也会被销毁。
实际上,您可以访问数据并且不会收到任何错误,但是您不应该考虑这种情况,因为这是不安全的。仅认为这是错误的。
为了获得所需的内容,您应该自己对包含在集合中的对象进行内部初始化。Anunique_ptr<int>
可以做到这一点,因为返回值将在破坏集合时移动它并防止对象被释放。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句