Chinaunix

标题: 子函数中定义的对象 堆内存还是栈内存的问题 [打印本页]

作者: gridbird    时间: 2013-07-12 09:31
标题: 子函数中定义的对象 堆内存还是栈内存的问题
在子函数中定义的所有局部变量都是存在栈内存中,那么如果在子函数中频繁定义多个类的对象,然后push_back 进stl vector, 搞不明白这个vector中的内容到底是存在栈内存还是堆内存中。 请看如下的示意代码:

类定义:

class A
{
   string strA;
   int intB;

public:
....
}

vector<A> testV;

// push 1000000 A 对象进 testV vector

func1 (&testV)
{
   for (int i=0; i< 1000000; i++)
  {
    A obA;
    obA.strA = "aaaaa";
    obA.intB  = 0;
   
     testV.push_back(obA);
}

请问 这个vector 的内容是存在栈内存还是堆内存? 如果函数1用另外一种实现(存指针,如下:)和上面那种直接push_back对象,具体有什么区别啊? 哪种效率高一些? push_back 操作是按位拷贝的吗?   

vector<A *> testV;

// push 1000000 A 对象进 testV vector

func1 (&testV)
{
   for (int i=0; i< 1000000; i++)
  {
    A *obA;
    obA->strA = "aaaaa";
    obA->intB  = 0;
   
     testV.push_back(obA);
}


多谢!

作者: linux_c_py_php    时间: 2013-07-12 14:17
。。。 你没分配内存啊,哥哥。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2