C++20 读书笔记(2)

2022-10-25 16:53:58 浏览数 (1)

本篇介绍

本篇继续c 20的学习

传参

都知道在传递比较复杂的参数的时候,最好用const &,如果要支持左值应用和右值引用,那么就需要写一对函数支持重载了:

代码语言:javascript复制
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;
};

这时候如果要简化,那么就可以按值传递:

代码语言:javascript复制
class DataHolder {
public:
void setData(std::vector<int> data) { m_data = std::move(data); }
private:
std::vector<int> m_data;
};

按左值引用传递会拷贝一次,按右值引用不拷贝,但是函数需要重载,而按值传递,也是左值引用传递会拷贝一次,按右值引用不拷贝,效果一样,而且还更简单。

Ref-Qualified

有时候有的方法希望是临时对象调用的,有的方法希望是非临时对象调用的,这时候可以按照如下方式操作:

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
float asFloat { 1.23f };
auto asUint { bit_cast<unsigned int>(asFloat) };
if (bit_cast<float>(asUint) == asFloat) { cout << "Roundtrip success." << endl; }

0 人点赞