C++性病载体含量范围
C++ std vector content scope
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
的目的。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 矢量下标超出SFML游戏中的范围