C++ std vector 内容范围

标签 c++ scope stdvector

class example1
{
    private:
    int i;
public:
    example1(){i = 1;}
    int getI(){return i;}
};

class example2
{
public:
    example2(){}
    vector<example2> this_vector_wont_compile(3);
    vector <example2> theVec;
    void addVec()
    {
        //what's the scope of this?
        //does push_back create a pointer
        //to which a deep copy of the example1 instance
        //returned by the constructor is performed?
        theVec.push_back(example2());
    }
};
int main()
{
    example2 theExample;
    theExample.theVec[0]; //can be accessed, instance of example1 in scope.
    return 0;
}

嗨,我正在尝试了解使用 std::vector 的底层内存操作。上面的例子是我过去如何使用它们的,而不质疑它是如何完成的。

example2() 构造函数返回一个实例,该实例在 addVec() 函数结束时超出范围,那么 theVec 如何添加它,同时将其保持在与 theVec 一样长的范围内?

另外,为什么在类中声明 std::vector 具有常量大小会产生编译器错误,以及如何避免?

最佳答案

当您调用 theVec.push_back(example2()); 时, vector 会创建 example2 临时实例的拷贝,并将其传递给 push_back。这将使用类的复制构造函数来完成,当您没有显式创建复制构造函数时,编译器将自动生成该构造函数。

我不完全确定您在声明具有常量大小的 std::vector 时要问什么。 std::vector 根据定义,没有恒定的大小。但是,您可以通过像这样定义构造函数来构造它的初始大小:

class example2 
{
    example2() : theVec( 10 ) {};
    std::vector< example2 > theVec;
    ....
}

关于C++ std vector 内容范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489636/

相关文章:

c++ - 不使用库的字符串的字符删除和频率

c# - 在 C# 中从串口接收数据有问题吗?

for循环中的Python变量范围

c++ - 如何在不复制的情况下将过滤 vector 的结果存储在另一个 vector 中

c++ - 如何将一系列数据从 char 数组复制到 vector 中?

c++ - 从数组转换为 vector 的边界

c++ - wxWidgets 对话框布局与 Gridbagsizer

c++ - STL 重载 vector 赋值

JavaScript for/循环作用域

Javascript 变量作用域之谜