vector push_back普通指针的感想

vector push_back普通指针的感想

#include <vector>
#include <iostream>

//vector push_back是变量内容的拷贝,而且是深拷贝,对于数据来说,变量中存储的内容就是变量值。
//对于指针来说,变量内存储的内容是指针指向的内存地址。
/*1 2 3 4 
  5 5 5 5
  1 2 3 4*/

void test1()
{
  std::vector<int> vec;
  int num1 = 1;
  int num2 = 2;
  int num3 = 3;
  int num4 = 4;
  vec.push_back(num1);
  vec.push_back(num2);
  vec.push_back(num3);
  vec.push_back(num4);
  for(const auto& i : vec){
    std::cout << i << " ";
  }
  std::cout << std::endl;

  num1 = num2 = num3 = num4 = 5;
  std::cout << num1 << " "
            << num2 << " "
            << num3 << " "
            << num4 << std::endl;

  for(const auto& i : vec){
    std::cout << i << " ";
  }
  std::cout << std::endl;
}

void test2()
{
  std::vector<int*> vec;
  int *num1 = new int(1);
  int *num2 = new int(2);
  int *num3 = new int(3);
  int *num4 = new int(4);
  vec.push_back(num1);
  vec.push_back(num2);
  vec.push_back(num3);
  vec.push_back(num4);
  for(const auto& i : vec){
    std::cout << *i << " ";
  }
  std::cout << std::endl;

  //指针指向的地址没有变化,而是指向的地址内存储的东西发生了变化
  *num1 = *num2 = *num3 = *num4 = 5;
  std::cout << *num1 << " "
            << *num2 << " "
            << *num3 << " "
            << *num4 << std::endl;

  for(const auto& i : vec){
    std::cout << *i << " ";
  }
  std::cout << std::endl;
}

void test3()
{
  std::vector<int*> pInt;
	for (int i = 0; i < 10; i++)
	{
		int *a = new int;
		*a = i;
		pInt.push_back(a);//没有delete,所以堆上的数据没有被释放,存在内存泄漏问题
    std::cout << &a << std::endl;//可以看到指针a一直是同一个地址,因为是临时变量,出了作用域变量就自动释放了,并且将内存分配给新的变量
	}
  for(const auto& i : pInt){
    std::cout << i << " ";
  }
  std::cout << std::endl;
  for(const auto& i : pInt){
    std::cout << *i << " ";
  }
  std::cout << std::endl;
}

int main(int argc, char** argv)
{
  test1();
  test2();
  test3();
}

输出结果:
vector push_back普通指针的感想

上一篇:逆向地基2-数据与c


下一篇:java中GUI相关知识点