C++11 入门

目录

1. C++11简介

2. 列表初始化

3. 变量类型推导

4. 范围for循环

5. 新增加容器---静态数组array、forward_list以及unordered系列

6. 默认成员函数

7.左值引用VS右值引用


1. C++11简介


C++11名字的由来

在2003年C++标准委员会曾经提交了一份技术勘误表(简称TC1),使得C++03这个名字已经取代了C++98称为C++11之前的最新C++标准名称。不过由于TC1主要是对C++98标准中的漏洞进行修复,语言的核心部分则没有改动,因此人们习惯性的把两个标准合并称为C++98/03标准。从C++0x到C++11,C++标准10年磨一剑,第二个真正意义上的标准珊珊来迟。相比于C++98/03,C++11则带来了数量可观的变化,其中包含了约140个新特性,以及对C++03标准中约600个缺陷的修正,这使得C++11更像是从C++98/03中孕育出的一种新语言。相比较而言,C++11能更好地用于系统开发和库开发、语法更加泛华和简单化、更加稳定和安全,不仅功能更强大,而且能提升程序员的开发效率


2. 列表初始化


引入:C++98中{}的初始化问题

在C++98中,标准允许使用花括号{}对数组元素进行统一的列表初始值设定。比如:
int array1[] = {1,2,3,4,5};
int array2[5] = {0};
对于一些自定义的类型,却无法使用这样的初始化。比如:
vector<int>nums{1,2,3,4};
就无法通过编译,导致每次定义vector时,都需要先把vector定义出来,然后使用循环对其赋初始值,非常不方便。C++11扩大了用大括号括起的列表(初始化列表)的使用范围,使其可用于所有的内置类型和用户自定 义的类型,使用初始化列表时,可添加等号(=),也可不添加
以下格式C++11是支持的
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <array>
#include <string>
#include <assert.h>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
		:_year(year)
		, _month(month)
		, _day(day)
	{
		cout << "Date(int year, int month, int day)" << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	int x1 = 1;
	int x2 = { 2 };//不建议使用
	int x3{ 2 };   // 不建议使用
	//cout << typeid(x2).name() << endl;//int
	//cout << typeid(x2).name() << endl;//int

	//本质都是在调用构造函数
	Date d1(2023, 8, 22);
	Date d2 = { 2023,8,23 };
	Date d3{ 2023,8,24 };

	//调用支持 list (initializer_list<value_type> il,       const allocator_type& alloc = allocator_type());
	vector<int> v1 = { 1,2,3,4 };
	vector<int> v2{ 1,2,3,4,5 };
	list<int> l1{ 5,6,7,8 };
	list<int> l2 = { 3,4,5,6 };

	//auto x= { 1,2,3,4 };
	//cout << typeid(x).name() << endl;

	vector<Date>v3 = { d1,d2,d3 };
	vector<Date>v4{ d1,d2,d3 };

	string s1 = "hello";

	//构造
	map<string, string>dict = { {"apple","苹果"},{"banana","香蕉"},{"fruit","水果"} };
	//赋值重载
	initializer_list<pair<const string, string>> kvil = { { "left", "左边" }, { "left", "左边" } };
	dict = kvil;

	return 0;
}
代码运行结果:

3. 变量类型推导

关键字auto

C++11中,可以使用auto来根据变量初始化表达式类型推导变量的实际类型,可以给程序的书写提供许多方 便。将程序中c与it的类型换成auto,程序可以通过编译,而且更加简洁。
#include <map>
#include <string>
int main()
{
	short a = 32670;
	short b = 32670;

	// c如果给成short,会造成数据丢失,如果能够让编译器根据a+b的结果推导c的实际类型,就不会存
	//在问题
		short c = a + b;

	std::map<std::string, std::string> m1{ {"apple", "苹果"}, {"banana","香蕉"} };
	// 使用迭代器遍历容器, 迭代器类型太繁琐
	std::map<std::string, std::string>::iterator it = m1.begin();
	auto e = m1.begin();//和上面这行等价

	while (it != m1.end())
	{
		cout << it->first << " " << it->second << endl;
		++it;
	}

	

	return 0;
}

auto使用的前提是:必须要对auto声明的类型进行初始化,否则编译器无法推导出auto的实际类型。但有 时候可能需要根据表达式运行完成之后结果的类型进行推导,因为编译期间,代码不会运行,此时auto也就无能为力。下面这种情况自然是无法推导的。
template<class T1, class T2>
T1 Add(const T1& left, const T2& right)
{
 return left + right;
}
如果能用加完之后结果的实际类型作为函数的返回值类型就不会出错,但这需要程序运行完才能知道结果的 实际类型,即RTTI(Run-Time Type Identification 运行时类型识别)
C++98中确实已经支持RTTI:
        typeid只能查看类型不能用其结果类定义类型
        dynamic_cast只能应用于含有虚函数的继承体系中
        运行时类型识别的缺陷是降低程序运行的效率。

关键字typeid和decltype

decltype是根据表达式的实际类型推演出定义变量时所用的类型,比如:

1. 推演表达式类型作为变量的定义类型

int main()
{
 int a = 10;
 int b = 20;
 
 // 用decltype推演a+b的实际类型,作为定义c的类型
 decltype(a+b) c;
 cout<<typeid(c).name()<<endl;
 return 0;
}

2. 推演函数返回值的类型

void* GetMemory(size_t size)
{
 return malloc(size);
}
int main()
{
 // 如果没有带参数,推导函数的类型
 cout << typeid(decltype(GetMemory)).name() << endl;
 
 // 如果带参数列表,推导的是函数返回值的类型,注意:此处只是推演,不会执行函数
 cout << typeid(decltype(GetMemory(0))).name() <<endl;
 
 return 0;
}

比较typeid和decltype 

int main()
{
	int x = 10;
	//typeid(x)y1 = 5;//error
	// typeid拿到只是类型的字符串,不能用这个再去定义对象什么的
	decltype(x) y1 = 20;
	cout << typeid(y1).name() <<" y1:" << y1 << endl;//int
	auto y2 = 3.14;
	cout << typeid(y2).name()<<" y2:"<<y2 << endl;
	return 0;
}

运行结果:


4. 范围for循环

上面我们提到了用迭代器遍历其实挺麻烦的,我们有更直接的方法--范围for

这个代码想来有的小伙伴页见过,作用是统计数组中数字的个数

#include<unordered_map>
#include<vector>
using std::vector;
using  std::unordered_map;
 
int main()
{
	unordered_map<int,int> count;
	vector<int>nums{ 1,1,2,2,2,3,4,4,4,4,5 };
	for (auto num : nums)
	{
		count[num]++;
	}
	for (auto e : count)
		cout << e.first << "出现了 "<<e.second<<" 次"<<endl;

	return 0;
}

实际上范围for的底层是封装了迭代器的。


5. 新增加容器---静态数组array、forward_list以及unordered系列

array官方文档 : cplusplus.com/reference/array/

 新增的array主要是为了替代C语言中的静态数组

//C++11新增的array容器测试
int main()
{
	const size_t N = 100;
	int a1[N];

	// C语言数组越界检查,越界读基本检查不出来,越界写是抽查
	a1[N];
	//a1[N] = 1;
	a1[N+5] = 1;


	// 越界读写都可以被检查出来
	// 实际情况:array用得很少,一方面大家用c数组用惯了
	// 用array不如用vector + resize去替代c数组

	array<int, N> a2;
	a2[N];
	a2[N] = 1;
	a2[N + 5] = 1;

	return 0;
}
unorder_map 和 unordered_set 的查找和排序效率都比map和set好,详细的后面有时间整理出来

6. 默认成员函数控

C++11之后就有了8个构造函数,分别是 构造函数、拷贝构造函数、运算符重载、析构 函数和&和const&的重载、 移动构造、移动拷贝构造(新增) 等函数。如果在类中显式定义了,编译器将不会重新生 成默认版本

案例1

//模拟实现的string, 方便观察现象
namespace hy
{
	class string
	{
	public:
		typedef char* iterator;
		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		string(const char* str = "")
			:_size(strlen(str))
			, _capacity(_size)
		{
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

		// 拷贝构造
		string(const string& s)
			:_str(nullptr)
		{
			cout << "string(const string& s) -- 拷贝构造(深拷贝)" << endl;

			//string tmp(s._str);
			//swap(s);

			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
		}

		// 移动构造
		string(string&& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			cout << "string(string&& s) -- 资源转移" << endl;
			swap(s);
		}

		// 拷贝赋值
		string& operator=(const string& s)
		{
			cout << "string& operator=(string s) -- 拷贝赋值(深拷贝)" << endl;
			string tmp(s);
			swap(tmp);

			return *this;
		}

		// 移动赋值
		string& operator=(string&& s)
		{
			cout << "string& operator=(string s) -- 移动赋值(资源移动)" << endl;
			swap(s);

			return *this;
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;

				_capacity = n;
			}
		}

		void push_back(char ch)
		{
			if (_size >= _capacity)
			{
				size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newcapacity);
			}

			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}

		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

		const char* c_str() const
		{
			return _str;
		}
	private:
		char* _str;
		size_t _size;
		size_t _capacity;
	};
	
}
hy::string to_string(int value)
{
	bool flag = true;
	if (value < 0)
	{
		flag = false;
		value = 0 - value;
	}

	hy::string str;
	while (value > 0)
	{
		int x = value % 10;
		value /= 10;

		str += ('0' + x);
	}

	if (flag == false)
	{
		str += '-';
	}

	std::reverse(str.begin(), str.end());
	return str;
}

// 拷贝构造和移动构造
int main()
{
	hy::string ret =  to_string(-3456);

	hy::string s1("1111111");
	hy::string s2(s1);

	return 0;
}

 案例2

int main()
{
	hy::string str1("hello");
	hy::string str2(str1); //  拷贝构造
	hy::string str3(std::move(str1)); // 移动构造


	std::string s1("hello world");
	std::string s2(s1); // 拷贝构造

	// std::string s3(s1+s2);
	std::string s3 = s1 + s2; // 移动构造
	std::string s4 = move(s1);

	return 0;
}

案例3 

int main()
{
	std::vector<hy::string> v;
	hy::string s1("hello");
	v.push_back(s1);

	cout << "----------------------------------" << endl;

	v.push_back(hy::string("world"));
	//v.push_back("world");

	cout << "===================================" << endl;

	std::list<hy::string> lt;
	//bit::string s1("hello");
	lt.push_back(s1);

	cout << "----------------------------------" << endl;

	lt.push_back(hy::string("world"));
	//lt.push_back("world");

	return 0;
}

案例4 

class Person
{
public:
	Person(const char* name = "", int age = 0)
		:_name(name)
		, _age(age)
	{}

	// 会默认生成拷贝构造+移动构造

	// 不想让Person对象拷贝
	//Person(const Person& p) = delete;

	/*~Person()
	{}*/

private:
	hy::string _name;
	int _age;
};

int main()
{
	Person s1("张三", 7);
	Person s2 = s1; // 拷贝构造
	Person s3 = std::move(s1); // 移动构造 (没有移动构造,再调用拷贝构造)
	//Person s4;
	//s4 = std::move(s2);

	return 0;
}


7.左值引用VS右值引用

左值与右值是C语言中的概念,但C标准并没有给出严格的区分方式,一般认为:可以放在=左边的,或者能够取地址的称为左值,只能放在=右边的,或者不能取地址的称为右值,但是也不一定完全正确。
int main()
{
	//左值:可以取地址的值-->内存中有位这个变量开辟空间
	/*int a = 20;
	const int b = 5;
	int* p = &a;
	*p = 100;
	//a,b,p都是左值*/

	//以下的p、b、c、*p都是左值
	int* p = new int(0);
	int b = 1;
	const int c = 2;

	// 以下几个是对上面左值的左值引用
	int*& rp = p;
	int& rb = b;
	const int& rc = c;
	int& pvalue = *p;

	//右值:不能取地址
	double x = 1.1, y = 2.2;
	10;
	x + y;
	fmin(x, y);
	//cout << &10 << endl;
	//cout << &(x + y) << endl;

	// 以下几个都是对右值的右值引用
	int&& rr1 = 10;
	double&& rr2 = x + y;
	double&& rr3 = fmin(x, y);

	

	return 0;
}
因此关于左值与右值的区分不是很好区分,一般认为:
1. 普通类型的变量,因为有名字,可以取地址,都认为是左值。
2. const修饰的常量,不可修改,只读类型的,理论应该按照右值对待,但因为其可以取地址(如果只是 const类型常量的定义,编译器不给其开辟空间,如果对该常量取地址时,编译器才为其开辟空间), C++11认为其是左值。
3. 如果表达式的运行结果是一个临时变量或者对象,认为是右值。
4. 如果表达式运行结果或单个变量是一个引用则认为是左值。
总结:
1. 不能简单地通过能否放在=左侧右侧或者取地址来判断左值或者右值,要根据表达式结果或变量的性质
判断,比如上述:c常量
2. 能得到引用的表达式一定能够作为引用,否则就用常引用。
C++11对右值进行了严格的区分:
C语言中的纯右值,比如:a+b, 100
将亡值。比如:表达式的中间结果、函数按照值的方式进行返回。
示例 1 :
void Fun(int& x) { cout << "左值引用" << endl; }
void Fun(const int& x) { cout << "const 左值引用" << endl; }

void Fun(int&& x) { cout << "右值引用" << endl; }
void Fun(const int&& x) { cout << "const 右值引用" << endl; }


// 万能引用:t既能引用左值,也能引用右值
// 引用折叠
template<typename T>
void PerfectForward(T&& t)
{
	// 完美转发:保持t引用对象属性
	Fun(std::forward<T>(t));
}

#include"list.h"

int main()
{
	PerfectForward(10);           // 右值

	int a;
	PerfectForward(a);            // 左值
	PerfectForward(std::move(a)); // 右值

	const int b = 8;
	PerfectForward(b);		      // const 左值
	PerfectForward(std::move(b)); // const 右值

	hy::list<hy::string> lt;
	hy::string s1("hello");
	lt.push_back(s1);
	
	cout << "----------------------------------" << endl;
	
	//lt.push_back(bit::string("world"));
	lt.push_back("world");

	return 0;
}

问题:

 左值引用可以引用右值吗? 右值引用可以引用左值吗?

示例2:

    //有条件的支持
	// 左值引用可以引用右值吗? const的左值引用可以
	//double& r1 = x + y;  //error
	const double& r1 = x + y;//有条件的

	// 右值引用可以引用左值吗?可以引用move以后的左值
	//int&& rr5 = b;
	int&& rr5 = move(b);

结论1 :const修饰的左值可以引用右值,因为本身不可修改,因而产生了万能引用

//万能引用
// x既能接收左值,也能接收右值
template<class T>
void Func(const T& x)
{}

结论2 : 右值不能引用左值,但是可以引用move后的左值,使用move有一定风险,要小心使用。

int main()
{
	double x = 1.1, y = 2.2;
	int&& rr1 = 10;
	const double&& rr2 = x + y;
	rr1 = 20;
	//rr2 = 5.5;//error
	cout << rr1 << " " << rr2 << endl;
	return 0;
}

应用

//实现一个只能在对上创建对象的类
class HeapOnly 
{
public:
	HeapOnly()
	{
		_str = new char[10];
	}
	~HeapOnly() = delete;
	void Destory()
	{
		delete[] _str;
		operator delete(this);
	}
private:
	char* _str;
	//...
};
//使用

int main()
{
	//HeapOnly hp1;
	//static HeapOnly hp2;

	HeapOnly* ptr = new HeapOnly;

	//delete ptr;

	ptr->Destroy();
	//operator delete(ptr);

	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值