Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c++ - Does std::array<> guarantee allocation on the stack only?

Is std::array<int,10> (without myself using new) guaranteed to be allocated in the stack rather then the heap by the C++-Standard?

To be clear, I do not mean new std::array<int, 10>. I mainly wonder, if the standard library is allowed to use new inside its implementation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TL;DR: yes, it is on the stack.


The longer story:

C++ has no concept of stack or heap. Those are implementation details, and there is at least one platform that does not use a traditional stack (but rather linked list of heap allocations for it).

It has automatic storage and the free store. new accesses the free store, and variables "on the stack" go into automatic storage.

In practice, in order to allocate things on the free store, you have to risk an out of memory exception. So the general rule is things that guarantee they do not throw must be using automatic storage. array makes this guarantee (except whatever is in it can throw, naturally). It is also an aggregate of plain old data, effectively forced to look like:

template<class T,std::size_t N>
struct array {
  T __no_fixed_name__[N];
  // non-constructor/destructor methods omitted as they are noise at this point
};

In theory it could be implemented by the compiler via magic that is not actual C++, but there is no need for that, so nobody bothers.

So in conclusion: yes, std::array is on the stack.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...