简体   繁体   English

我可以在超出范围后保留矢量数据吗

[英]Can I keep vector data even after out of scope

I come from a C background.我来自 C 背景。 I used to allocate memory/array, for example, sending it to somewhere else, and the pointer stayed there, even after, the scope where it was allocated was destroyed.我曾经分配内存/数组,例如,将其发送到其他地方,指针留在那儿,即使在分配它的范围被销毁之后。

Now, if I do the same with vectors: initialize, pass it by reference, and then keep that reference saved somewhere.现在,如果我对向量做同样的事情:初始化,通过引用传递它,然后将该引用保存在某个地方。 After the initial method, that actually created the vector, goes out of scope, would it be destroyed?在实际创建向量的初始方法超出范围后,它会被销毁吗? Or as the pointer to it is still saved, it will be kept.或者因为指向它的指针仍然被保存,所以它会被保留。

std::vector frees the memory it holds when it is destroyed. std::vector在它被销毁时释放它持有的内存。 Holding a reference to an object that gets destroyed is very bad.持有一个被销毁的对象的引用是非常糟糕的。 Accessing it is UB.访问它是 UB。 General rule: Do not store references, only use them where you can be sure that the object exists for the entire scope, eg as parameter of a function.一般规则:不要存储引用,仅在您可以确定对象在整个范围内都存在的地方使用它们,例如作为函数的参数。

If you want to keep a copy of the data, simply copy the std::vector .如果您想保留数据的副本,只需复制std::vector即可。 No reference needed.无需参考。

If you want to be able to access the data from different locations, and have it live as long as at least one location still has a reference/pointer to it, don't use std::vector , use std::shared_ptr .如果您希望能够从不同的位置访问数据,并且只要至少一个位置仍然有指向它的引用/指针就可以让它一直存在,请不要使用std::vector ,使用std::shared_ptr

If you want to combine the benefits of std::vector with the benefits of shared memory that lives until the last place lets go of it, combine them: std::shared_ptr<std::vector<...>> .如果您想将std::vector的优点与共享内存的优点结合起来,直到最后一个地方放开它,请将它们结合起来: std::shared_ptr<std::vector<...>>

If you want to have the std::vector live in one place for a bit, and then live in another place but not in the first place anymore, use move semantics :如果你想让std::vector在一个地方住一段时间,然后住在另一个地方但不再在第一位,请使用移动语义

std::vector<int> foo = {1, 2, 3};
std::vector<int> bar = std::move(foo); // bar now holds the data that foo held, foo is empty, no copy was performed

A pointer to an array on the stack will not keep the array alive, I suppose thats the same in C. Now a vector is not an array.指向堆栈上数组的指针不会使数组保持活动状态,我想在 C 中也是如此。现在向量不是数组。 It is a wrapper around a heap allocated array which frees the memory of the array when it goes out of scope.它是堆分配数组的包装器,当它超出范围时释放数组的内存。

... because a pointer to it is still saved it will still be kept? ...因为指向它的指针仍被保存,它仍将被保留?

No!不! A pointer or reference to a std::vector will not keep the vector alive.指向std::vector的指针或引用不会使向量保持活动状态。 The canonical wrong example is:典型的错误示例是:

std::vector<T>& foo() {
    std::vector<T> x;
    return x;
}                      // baaam !

The reference returned from the function is dangling.从函数返回的引用是悬空的。 YOu cannot do anything with it.你不能用它做任何事。 The correct way would be to return by value and rely on return value optimization:正确的方法是按值返回并依赖返回值优化:

std::vector<T> foo() {
    std::vector<T> x;
    return x;
}

If you do:如果你这样做:

auto y = foo();

No copying is involved, thanks to NRVO.由于 NRVO,不涉及复制。

PS: Compilers should warn you about returning a reference to a local variable. PS:编译器应该警告您返回对局部变量的引用。

No if I do the same with vectors, I initialize a vector, pass it by reference, then keep the reference saved somewhere.不,如果我对向量做同样的事情,我会初始化一个向量,通过引用传递它,然后将引用保存在某个地方。 After the initial method that actually created the vector goes out of scope, would it be destoryed?在实际创建向量的初始方法超出范围后,它会被销毁吗?

Yes.是的。

or because a pointer to it is still saved it will still be kept?还是因为指向它的指针仍被保存,它仍将被保留?

No.不。


You can have dangling pointers in C++ just like you can in C. It's exactly the same.就像在 C 中一样,您可以在 C++ 中使用悬挂指针。完全一样。

This is also often the case for references (though in some cases the lifetime of the object is extended for a little bit).引用也经常出现这种情况(尽管在某些情况下对象的生命周期会延长一点)。

It is true that the vector's data is internally managed by the vector, but that's by-the-by since you're asking about the vector itself.向量的数据确实由向量在内部管理,但这是顺便说一句,因为你问的是向量本身。 Forget the vector and ask the same question about an int , then you'll realise the answer is just as you'd expect it to be in C.忘记 vector 并问关于int的相同问题,然后你会意识到答案就像你期望的那样在 C 中。

The existing answers are good, will add here:现有的答案都不错,这里补充一下:

block A
{
vector<int> my_vec(10, 0);
//...something...
}
block B

The my_vec vector will go out of scope and be destroyed at the closing bracket. my_vec 向量将超出范围并在右括号处被销毁。 Now that's stl (Standard Template Library) vectors.现在是 stl(标准模板库)向量。

You can also use C-style arrays (but with different syntax).您还可以使用 C 风格的数组(但语法不同)。 For very large arrays, I have found the allocation time with a dynamically-allocated array to be faster than STL vectors.对于非常大的数组,我发现动态分配数组的分配时间比 STL 向量更快。

//static, goes out of scope and memory handled at the end of code block
int arr0[10];

//dynamic, not destroyed unless delete called.
int* arr1 = new int[10];
//...work with arr1...
delete [] arr1;

Just like in C, you need to take care of de-allocating any memory you create using new .就像在 C 中一样,您需要注意取消分配使用new创建的任何内存。

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

相关问题 矢量数据超出范围后将丢失 - Vector data is lost after it goes out of scope 是否可以返回对 std::vector 中数据的引用,并在向量超出 scope 后保留该引用? - Is it possible to return an a reference to the data in an std::vector, and preserve that reference after the vector goes out of scope? 排序后如何保持向量中重复项的顺序? - How can I keep the order of duplicates in a vector after sorting it? 向量 <string> 超出范围后不会清除内存 - vector<string> does not clear memory after out of scope 变量超出范围后如何保留矢量值? - How vector value is retained after the variable goes out of scope? 将局部变量保存到全局向量中,为什么离开局部范围后才能得到这些局部变量? - save local variables into global vector, why can i got these local variables after leaving local scope? 当向量超出范围时,防止数据被释放 - preventing data from being freed when vector goes out of scope 带OpenCV的Visual Studio:即使程序退出后,我也可以保持图像窗口打开吗? - Visual Studio with OpenCV: Can I keep the image windows open even after program exits? 为什么这个向量向量超出范围? - Why is this vector of vectors out of scope? 超出范围的向量内的向量 - vector within a vector going out of scope
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM