我需要对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;
}
如果然后我使用new运算符在堆上创建了一个示例对象:
Example* ex = new Example();
并向每个容器添加一千个条目,我添加的条目也将位于堆上吗?如果是的话,那么如果我做的话会有所不同:
class Example{
// methods to add stuff to containers
//...
std::hash_map<std::string,int>* map;
std::vector<std::string>* vec;
}
然后
Example* ex = new Example();
最佳答案
无论hash_map
或vector
的存储位置如何,它们所包含的数据将始终位于堆中。
例子1
int main() {
hash_map<T> table;
}
table
在堆栈上。 table
包含的数据在堆上。例子2
int main() {
hash_map<T> *table = new hash_map<T>();
}
table
是存在于堆栈中的指针。 *table
是堆上存在的hash_map
。 *table
包含的数据仍在堆上。例子3
hash_map<T> table;
int main() {
...
}
table
不在堆或堆栈中。指向的数据table
仍在堆上。关于c++ - C++堆/堆栈说明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29458754/