C++ 中的深浅拷贝

浅拷贝是逐字节拷贝对象的成员变量 ,这里如果成员变量是指针,很明显,只拷贝了指针储存的地址并没有去拷贝指针指向的值。由此引出了C++中的深浅拷贝。拷贝赋值与拷贝构造类似,这里以拷贝构造为例来说明深浅拷贝。

首先,这里我们有一个类,先不写拷贝构造函数:

cpp 复制代码
#include <iostream>
#include <vector>

class TestClass {
public:
  TestClass(int num)
    : num_{ 1 },
    num_ptr_{ new int(num) }
  {
    std::cout << "default constructor\n";
  }

  ~TestClass() {
    num_ptr_ = nullptr;
    std::cout << "destructor\n";
  }

private:
  int num_;
  int* num_ptr_;
};

int main() {
  int num{ 1 };
  TestClass test_default{ num }; // 默认构造
  TestClass test_move{ test_default };  // 拷贝构造

  std::cout << "Program finished!\n";
  return 0;
}

一个类如果不显示写拷贝构造函数,那么编译器会自动为这个类对象创建一个拷贝构造函数,默认行为是逐字节拷贝对象成员变量,我们看调试结果:

两个对象中num_ptr_地址相同,指向的值相同,这就是浅拷贝。

接着我们补充拷贝构造函数:

cpp 复制代码
// 拷贝构造
TestClass(const TestClass& other)
  : num_{ other.num_ },
  num_ptr_{ new int(*other.num_ptr_) }
{
  std::cout << "copy constructor\n";
}

然后看调试结果:

两个对象中num_ptr_地址不同,指向的值相同,这就是深拷贝。深拷贝确保了两个对象没有共享同一份数据

写了拷贝构造函数以后,编译器不再自动生成,而是调用我们写的拷贝构造函数,具体是深拷贝还是浅拷贝取决于我们写的这个拷贝构造函数。如果我们在这个拷贝构造函数中做了浅拷贝,那么实际上最终还是浅拷贝。

最后贴出完整代码:

cpp 复制代码
#include <iostream>
#include <vector>

class TestClass {
public:
  TestClass(int num)
    : num_{ 1 },
    num_ptr_{ new int(num) }
  {
    std::cout << "default constructor\n";
  }

  // 拷贝构造
  TestClass(const TestClass& other)
    : num_{ other.num_ },
    num_ptr_{ new int(*other.num_ptr_) }
  {
    std::cout << "copy constructor\n";
  }

  ~TestClass() {
    num_ptr_ = nullptr;
    std::cout << "destructor\n";
  }

private:
  int num_;
  int* num_ptr_;
};

int main() {
  int num{ 1 };
  TestClass test_default{ num }; // 默认构造
  TestClass test_move{ test_default };  // 拷贝构造

  std::cout << "Program finished!\n";
  return 0;
}
相关推荐
会周易的程序员2 小时前
js-shm: 高性能 Node.js 共享内存模块
开发语言·javascript·c++·node.js·共享内存·shm
2023自学中2 小时前
imx6ull 开发板 贪吃蛇, C++11 SDL2 无硬件GPU优化版
linux·c++
anscos3 小时前
为CUDA 代码引入静态分析
c++·工业软件·功能检测
众少成多积小致巨3 小时前
C++ 规范参考(中)
c++
小保CPP3 小时前
OpenCV C++基于AI模型的场景文本识别(OCR)
c++·人工智能·opencv·计算机视觉·ocr
shylyly_3 小时前
C++中的类型转换
开发语言·c++·匿名对象·隐式类型转换·拷贝优化
jinyishu_3 小时前
哈希表原理与开放定址法C++实现
c++·哈希算法·散列表
小龙报4 小时前
【优选算法】1. 水果成蓝 2.找到字符串中所有字母的异位词
java·c语言·数据结构·数据库·c++·redis·算法
txzrxz5 小时前
数论:排列数、组合数、费马小定理、逆元、同余定理
c++·算法·数论·组合数·费马小定理·逆元·排列数
库克克6 小时前
【C++】STL 库
c++