zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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; }