关于变量范围的一些解释

mar*_*ega 1 c++ scope

/* simple class that has a vector of ints within it */
class A
{
public:
   vector<int> int_list;
};

/* some function that just returns an int, defined elsewhere */
int foo();

/* I want to fill the object's int_list up */
A a_obj;

int main() {
   for (int i = 0; i < 10; i++) {
      int num = foo();
      a_obj.int_list.push_back( num );
   }
}
Run Code Online (Sandbox Code Playgroud)

范围是否num仅限于for循环?一旦for循环退出,它会被销毁吗?如果我尝试访问人数a_objint_list会我不能够作为其中的数字将被破坏?

Lig*_*ica 5

范围是否num仅限于for循环?

一旦for循环退出,它会被销毁吗?

它会在每次迭代后被销毁,然后再次为下一次创建!

如果我尝试访问人数a_objint_list会我不能够作为其中的数字将被破坏?

容器存储副本,因此您不必担心这一点.

你只会遇到引用和指针这些问题.