Visual Studio 中 C++ 遇到 int -842150451 问题及解决方案

前言

在使用 C++ 的 list 容器存储自定义数据类型时,可能会遇到一些关于未初始化值的问题。最近在 Visual Studio 中编写代码时,我遇到了一个奇怪的问题:Person 类的身高属性在输出时显示为 -842150451。经过研究,我发现这是因为未初始化的成员变量导致的。

问题描述

在以下代码中,我们定义了一个 Person 类,其中包含姓名、年龄和身高三个属性,并使用 list 容器存储多个 Person 对象。

#include<iostream>
using namespace std;
#include<list>

// list 容器,排序案例,对于自定义数据类型,做排序

// 按照年龄进行升序,如果年龄相同按照身高进行降序
class Person
{
public:
	Person(string name, int age, int height)
	{
		this->m_Name = name;
		this->m_Age = age;
		this->m_Height = height;
		cout << "Created person: " << m_Name << ", Age: " << m_Age << ", Height: " << m_Height << endl;
	}

	string m_Name; // 姓名
	int m_Age; // 年龄
	int m_Height; // 身高
};
void test01()
{
	list<Person>L; // 创建容器

	// 准备数据
	Person p1("刘备", 35, 175);
	Person p2("曹操", 45, 180);
	Person p3("孙权", 40, 170);
	Person p4("赵云", 25, 190);
	Person p5("张飞", 35, 160);
	Person p6("关羽", 35, 200);

	// 插入数据
	L.push_back(p1);
	L.push_back(p2);
	L.push_back(p3);
	L.push_back(p4);
	L.push_back(p5);
	L.push_back(p6);

	for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
	{
		cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << " 身高:" << it->m_Height << endl;
	}
}
int main()
{
	test01();

	system("pause");

	return 0;
}

遇到的问题

在运行上述代码时,我发现身高的输出结果是 -842150451。这是因为 Person 类的成员变量在 list 容器中被复制时出现了问题,导致身高属性在未初始化的情况下被访问。

根据 StackOverflow 的解释,-842150451 是未初始化内存的常见表示,使用未初始化的变量会导致未定义的行为。

解决方案

1. 使用 emplace_back

为了避免不必要的复制并确保对象被正确构造,我决定使用 list 容器的 emplace_back 方法。该方法允许我们在容器内部直接构造对象,从而避免了复制的问题。

以下是修改后的代码:

#include<iostream>
using namespace std;
#include<list>

// list 容器,排序案例,对于自定义数据类型,做排序

// 按照年龄进行升序,如果年龄相同按照身高进行降序
class Person
{
public:
	Person(string name, int age, int height)
	{
		this->m_Name = name;
		this->m_Age = age;
		this->m_Height = height;
		cout << "Created person: " << m_Name << ", Age: " << m_Age << ", Height: " << m_Height << endl;
	}

	string m_Name; // 姓名
	int m_Age; // 年龄
	int m_Height; // 身高
};
void test01()
{
	list<Person>L; // 创建容器

	// 直接在 list 中构造数据
	L.emplace_back("刘备", 35, 175);
	L.emplace_back("曹操", 45, 180);
	L.emplace_back("孙权", 40, 170);
	L.emplace_back("赵云", 25, 190);
	L.emplace_back("张飞", 35, 160);
	L.emplace_back("关羽", 35, 200);

	for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
	{
		cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << " 身高:" << it->m_Height << endl;
	}
}
int main()
{
	test01();

	system("pause");

	return 0;
}

2. 输出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值