简体   繁体   English

堆栈std ::矢量范围

[英]Stack std::vector scope

im new to c++ and i'm finding hard to understand some vector behaviours. 我是c ++的新手,我很难理解一些矢量行为。 I was trying to implement a function to return an array of int and i found many suggestions to use a vector like this: 我试图实现一个函数来返回一个int数组,我发现很多建议使用这样的向量:

vector<int> myFunc()
{
    vector<int> myVector;
    //add elements to vector here...
    return myVector;
}

But from what i know 'myVector' is an object created on the stack, so isnt it going out of scope when the function end? 但据我所知,'myVector'是在堆栈上创建的对象,所以当函数结束时它不会超出范围吗? when does its destructor get called? 它的析构函数什么时候被调用? I know there are few other questions about returning vectors, but i need to clarify this specific point, hoping to not have duplicated a question. 我知道关于返回向量的其他问题很少,但我需要澄清这个具体点,希望不要重复一个问题。

Yes because myVector is allocated on the stack, as soon as the function returns, it goes out of scope. 是的,因为myVector是在堆栈上分配的,一旦函数返回,它就会超出范围。 But in this case that's ok! 但在这种情况下,没关系! Your function signature is 你的功能签名是

vector<int> myFunc()

which returns a copy of myVector so it doesn't matter that it's going out of scope since it's already being copied for the return. 它返回myVector副本 ,因此它已经超出范围并不重要,因为它已经被复制用于返回。

However if you changed it to something like 但是,如果你把它改成类似的东西

vector<int> & myFunc()

now your telling it not to copy myVector and you'll have a problem called a dangling reference since myVector will be destructed and you don't copy it but still try to use it. 现在你告诉它不要复制myVector你会遇到一个叫做悬挂引用的问题,因为myVector会被破坏,你不会复制它但仍然试图使用它。

Your code returns a copy of the myVector instance on the stack. 您的代码返回堆栈上myVector实例的副本 So it's OK it goes out of scope and is deleted (after return). 所以它可以超出范围并被删除(返回后)。

It does go out of scope, but when you return a class or struct, the compiler automatically makes a copy for you, so that your receiving object is filled in with the content of the original object. 它确实超出范围,但是当您返回一个类或结构时,编译器会自动为您创建一个副本,以便您的接收对象填充原始对象的内容。

Similar to: 如同:

vector<int> a;
vector<int> b;

... fill in vector a with stuff ... 

b = a; 

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

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