C ++ std向量内容范围

时间:2011-12-13 12:56:31

标签: 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 :: vectors的底层内存操作。上面的例子是我过去如何使用它们而不用质疑它是如何完成的。

当addVec()函数结束时,example2()构造函数返回一个超出作用域的实例,那么只要theVec是什么,theVec如何添加它,同时保持它的范围?

并且,如何将std :: vector声明为在类中具有常量大小会产生编译器错误,以及如何避免它?

2 个答案:

答案 0 :(得分:3)

当您调用theVec.push_back(example2());时,向量会创建传递给push_back的example2临时实例的副本。这将使用类的复制构造函数完成,编译器将自动生成,因为您没有明确创建它。

我不完全确定您要求声明std::vector具有恒定大小的内容。根据定义,std::vector没有恒定的大小。但是,您可以通过定义构造函数来构造初始大小:

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

答案 1 :(得分:1)

push_back中的addVec操作将构造的对象复制到其内部存储器中。原版超出范围并被销毁。

非编译部分没有意义。没有vector恒定大小的东西。这是std::array的用途。