当前位置:网站首页>STL教程9-容器元素深拷贝和浅拷贝问题
STL教程9-容器元素深拷贝和浅拷贝问题
2022-07-03 10:45:00 【贪睡的蜗牛】
浅拷贝问题的一个案例
定义一个类
下面有个指针成员,这样容易出现浅拷贝问题
class Person {
public:
char* name;
int age;
public:
Person(const char * name,int age) {
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
this->age = age;
}
~Person() {
if (this->name != NULL) {
delete[] this->name;
}
}
};
然后定义一个类的对象,把它放到容器里面
int main() {
const char* a = "name";
Person p(a, 20);
vector<Person>v;
v.push_back(p);
}
然后直接报错
原因在于外面的对象和vector里面对象的name指针都指向了同一块内存,在程序结束后,外面对象开始析构,析构完成后vector里面的元素也要析构, 这样同一块内存就析构了两次,就会发生错误
解决方法

修改后的代码
class Person {
public:
char* name;
int age;
public:
Person(const char * name,int age) {
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
this->age = age;
}
Person(const Person& p) {
this->name = new char[strlen(p.name) + 1];
strcpy(this->name, p.name);
this->age = p.age;
}
Person& operator=(const Person& p) {
if (this->name != NULL) {
delete[] this->name;
}
this->name = new char[strlen(p.name) + 1];
strcpy(this->name, p.name);
this->age = p.age;
return *this;
}
~Person() {
if (this->name != NULL) {
delete[] this->name;
}
}
};
重新运行没有崩溃
STL容器共性机制(重要)
STL所有容器提供的都是值语意,而非引用语意。容器执行插入元素操作时,内部内部实施了拷贝工作,将我们要插入的元素在拷贝一份放入到容器汇总,而不是将原数据元素直接放进容器中,因此我们提供的元素必须能够被拷贝(如果有指针需要自己去构造)。
最后
这里使用strcpy会出现问题,报错
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 C4996 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. map D:\store\server\leetcode\map\源.cpp 13
只需要在头部加上
#define _CRT_SECURE_NO_WARNINGS
边栏推荐
- The world's most popular font editor FontCreator tool
- Kubernetes 三打探针及探针方式
- How to mix embedded MCU, arm and DSP?
- Software testing weekly (issue 78): the more confident you are about the future, the more patient you are about the present.
- 多维度监控:智能监控的数据基础
- Gut | Yu Jun group of the Chinese University of Hong Kong revealed that smoking changes intestinal flora and promotes colorectal cancer (do not smoke)
- VPP three-layer network interconnection configuration
- 2022-07-02: what is the output of the following go language code? A: Compilation error; B:Panic; C:NaN。 package main import “fmt“ func mai
- C language log base zlog basic use
- Double linked list of linear list
猜你喜欢

一文搞懂Go语言Context

Redis things

Résumé des questions d'entrevue (2) Modèle io, ensemble, principe NiO, pénétration du cache, avalanche de rupture

Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure
![[OBS] configFile in ini format of OBS](/img/b2/0b130cee6ea884557a30e4b408f49e.png)
[OBS] configFile in ini format of OBS

进程与线程

Solve undefined reference to`__ aeabi_ Uidivmod 'and undefined reference to`__ aeabi_ Uidiv 'error

uniapp scroll view 解决高度自适应、弹框滚动穿透等问题。

FL Studio 20无限试用版水果编曲下载

导师对帮助研究生顺利完成学业提出了20条劝告:第一,不要有度假休息的打算.....
随机推荐
The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities
AMS Series 1 - AMS startup process
Phpcms prompt message page Jump showmessage
聊聊Flink框架中的状态管理机制
Oracle withdraw permission & create role
R语言使用原生包(基础导入包、graphics)中的hist函数可视化直方图(histogram plot)
Leetcode 46: full arrangement
ASP. Net hotel management system
C language two-dimensional array
Unique in the industry! Fada electronic contract is on the list of 36 krypton hard core technology enterprises
【学习笔记】dp 状态与转移
AMS series - application startup process
P3250 [HNOI2016] 网络 + [NECPC2022] F.Tree Path 树剖+线段树维护堆
Empire CMS no thumbnail smart tag (e:loop) two ways to judge whether there is a titlepic
Encapsulate a koa distributed locking middleware to solve the problem of idempotent or repeated requests
R语言使用gridExtra包的grid.arrange函数将ggplot2包的多个可视化图像横向组合起来,ncol参数自定义组合图列数、nrow参数自定义组合图行数
R语言使用aggregate函数计算dataframe数据分组聚合的均值(sum)、不设置na.rm计算的结果、如果分组中包含缺失值NA则计算结果也为NA
(2) Base
金额计算用 BigDecimal 就万无一失了?看看这五个坑吧~~
AIDL