C++堆/堆栈澄清

use*_*715 1 c++ heap stack initialization

我需要对C++内存分配做一些澄清,我只是举个例子

假设我已经创建了一个类A,它包含两个容器:一个hash_map和一个std :: vector,如下所示:

class Example{

// methods to add stuff to containers
//...

std::hash_map<std::string,int> map;
std::vector<std::string> vec;
}
Run Code Online (Sandbox Code Playgroud)

如果我然后使用new运算符在堆上创建示例对象:

Example* ex = new Example();
Run Code Online (Sandbox Code Playgroud)

并为每个容器添加一千个条目,我添加的条目也将位于堆上吗?如果是,那么如果我这样做会有什么不同:

 class Example{

    // methods to add stuff to containers
    //...

    std::hash_map<std::string,int>* map;
    std::vector<std::string>* vec;
    }
Run Code Online (Sandbox Code Playgroud)

然后 Example* ex = new Example();

Bil*_*nch 5

无论在何处hash_mapvector存储,它们包含的数据将始终在堆中.

例1

int main() {
    hash_map<T> table;
}
Run Code Online (Sandbox Code Playgroud)

table在堆栈上.table包含的数据位于堆上.

例2

int main() {
    hash_map<T> *table = new hash_map<T>();
}
Run Code Online (Sandbox Code Playgroud)

table是堆栈上存在的指针.*tablehash_map堆上存在的.*table包含的数据仍在堆上.

例3

hash_map<T> table;
int main() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

table不在堆或堆栈中.数据table指向仍然在堆上.

  • @ user2573715数据段.请参阅:http://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap (2认同)