2011-12-13 66 views
2
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的底层内存操作。上面的例子是我在过去如何使用它们而没有质疑它是如何完成的。C++ std向量内容范围

example2()构造函数在addVec()函数结束时返回一个超出范围的实例,那么Vec如何在添加它的同时将它保持在范围内,只要vec是?

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

回答

3

当您呼叫theVec.push_back(example2());时,向量将创建example2的临时实例的副本,并将其传递到push_back。这将使用该类的复制构造函数来完成,编译器将自动生成,因为您尚未明确创建该构造函数。

我不完全确定你在询问关于声明std::vector的常量大小。根据定义,std::vector没有恒定的大小。但是,您可以通过定义像这样的构造函数来构建初始大小:

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

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

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

+0

谢谢pmr和@obmarg,它完美地回答了我的问题。 –