我需要对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_mapvector的存储位置如何,它们所包含的数据将始终位于堆中。

例子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/

10-11 22:40
查看更多