yokila
yokila
Published on 2024-03-31 / 8 Visits
0
0

C++ 学习笔记(1)

0、说明

代码基于 C++14 标准

运行IDE:VS2022

操作系统:Windows11

1、空基类优化

空基类优化(empty base class optimization, EBCO/EBO)是一种编译器优化,可以令无非静态数据成员、无虚函数的基类实际占0字节(只要不会与同一类型的另一个对象或子对象分配在同一地址)。这种优化常用于具分配器的标准库类,如 std::vector、std::function、std::shared_ptr 等。

#include <iostream>

class Empty {};

class Derived : public Empty {
	int x;
};

class Derived2 : public Empty {
};

class Derived3 : public Empty {
	static int x;
};

class Derived12 : public Empty, Derived2 {
};

class Derived11 : public Empty {
	Empty e;
};

class Derived121 : public Empty, Derived2 {
	Empty e;
};

using std::cout;
using std::endl;

int main()
{
	cout << "Empty: " << sizeof(Empty) << endl;
	cout << "Derived: " << sizeof(Derived) << endl;
	cout << "Derived2: " << sizeof(Derived2) << endl;
	cout << "Derived3: " << sizeof(Derived3) << endl;
	cout << "Derived12: " << sizeof(Derived12) << endl;
	cout << "Derived11: " << sizeof(Derived11) << endl;
	cout << "Derived121: " << sizeof(Derived121) << endl;
}

输出结果:

相关参考链接:

2、valarray

valarray 是 C++98 引入的一个特殊容器,用于高效地保存和提供数组的数学运算。它支持逐元素的数学运算和各种形式的广义下标运算、切片和间接访问。与 vector不同,valarray 是专门为数学运算而设计的,可以在某些情况下提供更好的性能。

#include <iostream>
#include <valarray>

using std::cout;
using std::endl;
using std::valarray;

int main()
{
	valarray<int> v{ 0, 1, 2, 3 };
	valarray<int> v1{ 0, 1, 2, 3 };
	valarray<int> v2 = v + v1;
	valarray<int> v3 = v * v1;
	valarray<int> v4 = v * v;

	cout << v.sum() << endl;
	cout << v.size() << endl;

	for (int num : v2)
	{
		cout << num << " ";
	}
	cout << endl;
	for (int num : v3)
	{
		cout << num << " ";
	}
	cout << endl;
	for (int num : v4)
	{
		cout << num << " ";
	}
}

输出:



Comment