C++性病载体含量范围

C++ std vector content scope

本文关键字:范围 C++      更新时间:2023-10-16
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 的底层内存操作。 上面的例子是我过去如何使用它们,而不会质疑它是如何完成的。

example2(( 构造函数返回一个在 addVec(( 函数结束时超出范围的实例,那么 theVec 如何添加它,同时将其保持在 Vec 的作用域中?

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

当你调用theVec.push_back(example2());时,向量会创建一个 example2 的临时实例的副本,该实例被传递给 push_back 。 这将使用类的复制构造函数完成,编译器将自动生成该构造函数,因为您尚未显式创建一个。

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

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

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

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