[英]Creating objects on the stack
I have a class which contains a large vector 我有一个包含大向量的类
class myClass
{
public:
myClass(int size)
private:
vector<int> myVector;
}
myClass::myClass(int size)
{
myvector = vector<int>(size);
}
If I call myClass o(100000)
the object is created on the stack. 如果我调用
myClass o(100000)
,则会在堆栈上创建对象。 However, what is exactly on the stack ? 但是,堆栈上到底有什么? How much memory do I allocate from the stack ?
我要从堆栈分配多少内存? The contents of the vector should be allocated on the heap, right ?
向量的内容应该在堆上分配,对吗?
Can someone explain to me what exactly is on the stack and what is on the heap ? 有人可以向我解释堆栈中到底有什么,堆中到底有什么?
Essentially you can generalize std::vector
as 本质上,您可以将
std::vector
概括为
template<typename T>
struct vector {
T* data;
size_t size;
size_t capacity;
};
Individual implementations may vary but they'll usually look something like the above. 各个实现可能会有所不同,但是它们通常看起来像上面的样子。
So it's just this vector-container that is created on the stack, the array in which the data will be held is drawn from the heap. 因此,就是在堆栈上创建了这个向量容器,将要从堆中获取要保存数据的数组。
--- Edit --- -编辑-
For a given stack variable, you can tell how much stack space it requires with the sizeof
operator, eg 对于给定的堆栈变量,您可以使用
sizeof
运算符告诉它需要多少堆栈空间,例如
myClass o(100000);
std::cout << "o's size is " << sizeof(o) << "\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.