C++20 读书笔记(2)
C++ 20 读书笔记
2023-06-13 09:13:58 时间
本篇介绍
本篇继续c++20的学习
传参
都知道在传递比较复杂的参数的时候,最好用const &,如果要支持左值应用和右值引用,那么就需要写一对函数支持重载了:
class DataHolder {
public:
void setData(const std::vector<int>& data) { m_data = data; }
void setData(std::vector<int>&& data) { m_data = std::move(data); }
private:
std::vector<int> m_data;
};
这时候如果要简化,那么就可以按值传递:
class DataHolder {
public:
void setData(std::vector<int> data) { m_data = std::move(data); }
private:
std::vector<int> m_data;
};
按左值引用传递会拷贝一次,按右值引用不拷贝,但是函数需要重载,而按值传递,也是左值引用传递会拷贝一次,按右值引用不拷贝,效果一样,而且还更简单。
Ref-Qualified
有时候有的方法希望是临时对象调用的,有的方法希望是非临时对象调用的,这时候可以按照如下方式操作:
class TextHolder {
public:
TextHolder(string text) : m_text { move(text) } {} const string& getText() const & { return m_text; } string&& getText() && { return move(m_text); }
private:
string m_text;
};
inline
Since C++17, you can declare your static data members as inline. The benefit of this is that you do not have to allocate space for them in a source file
export class Spreadsheet {
// Omitted for brevity
private:
static inline size_t ms_counter { 0 };
};
bit_cast
It effectively interprets the bits of the source object as if they are the bits of the target object. bit_cast() requires that the size of the source and target objects are the same and that both are trivially copyable
float asFloat { 1.23f };
auto asUint { bit_cast<unsigned int>(asFloat) };
if (bit_cast<float>(asUint) == asFloat) { cout << "Roundtrip success." << endl; }
相关文章
- EasyC++20,while和do while循环
- C++构造函数的作用_c++什么是构造函数
- C++基本概念_c语言 c++区别
- C++运算符
- C++基础知识精髓
- c++的链表-链表入门(C++)
- c++的链表-C++实现简单链表
- C++ Boost 函数与回调应用
- C/C++ Qt 数据库QSql增删改查组件应用
- 使用 c++20 协程与 io_uring 实现高性能 web 服务器 part1:一个最简单的 echo server
- [C++STL教程]3.stack栈入门简明教程,小白都能理解~
- 【C++修炼之路】20.手撕红黑树
- C++空间配置器
- C++11 weak_ptr智能指针(一看即懂)
- C++常对象和常成员函数详解
- C++ setw:格式化输出(详解版)
- C++中Operator类型强制转换成员函数解析