1. ホーム
  2. C++

C++ std::vector要素のメモリ割り当て問題

2022-02-22 14:50:20
<パス

質問を見るには
C++のSTL vectorを使用する場合、以下の3つの書き方の違いは何ですか?また、それらのメモリ割り当てはどのようになりますか?

std::vector
 vec;
std::vector
* Vec = new std::vector
();
std::vector
First, the conclusion (assuming T is a well-defined class). 

For std::vector<T> vec; vec is on the stack (stack), and the elements of it, T, are kept on the heap (heap).
For std::vector<T>* Vec = new std::vector<T>(); vec and the elements of it, T, are stored on the heap.
For std::vector<T*> vec; vec is on the stack (stack), and the elements of it, T, are kept on the heap (heap); similar to the first case. Here's an experiment on the difference between the first case and the second case!
The following code declares a class A and a function IsObjectOnStack() to monitor whether the object is on the stack, which uses the Windows system API.
#include 

#include 

#include 
Here is the test for the first case.
int main()
{
    vector
 aa;
    int nCount = 2;
    for (int i = 0; i < nCount; i++)
    {
        A a;
        BOOL isOnStack = IsObjectOnStack(&a);
        if (isOnStack) cout << "Object a is created on the stack... " << '\n';
        else cout << "Object a is created on the heap... " << '\n';
        aa.push_back(a);
    }

    BOOL isOnStack = IsObjectOnStack(&(aa.at(0)));
    if (isOnStack) cout << "Element in std::vector created on stack... " << '\n';
    else cout << "Element in std::vector created on heap... " << '\n';


    return 0;
}
Run the result. 

As you can see std::vector<A> element A is created on the stack. And the object on the stack is copied to the heap by copy on push_back. Third case test. int main() { vector Run the result.
This one is obvious std::vector<A*> The objects in it are on the heap. After use, we must manually free the memory occupied by that object.
So, personally, I think the main difference between the two is that std::vector<T> and std::vector<T*> in which the element T is stored on the stack, and std::vector<T> There is no need to manually manage memory space, while std::vector<T*> need to manually delete to release the space on the stack. But when push_back std::vector<T> will be more efficient than std::vector<T*> with one more copy construction.
std::vector<T> vec;