美文网首页
C++20 读书笔记(2)

C++20 读书笔记(2)

作者: android小奉先 | 来源:发表于2022-10-05 18:38 被阅读0次

本篇介绍

本篇继续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; }

相关文章

  • C++20 读书笔记(2)

    本篇介绍 本篇继续c++20的学习 传参 都知道在传递比较复杂的参数的时候,最好用const &,如果要支持左值应...

  • C++20:标准库

    原文详见:C++20: The Library 在上篇文章 C++20:核心语言 中我们介绍了 C++20 的核心...

  • C++20:并发

    原文详见:C++20: Concurrency 本篇是 C++20 概览系列的最后一篇。今天我将介绍 C++ 新标...

  • C++20:概念之细节

    原文详见:C++20: Concepts, the Details 在我的上一篇文章 C++20:两个极端和概念的...

  • C++20 读书笔记(1)

    最近在看C++20相关的内容,本篇记录下遇到的比较好用的特性 Module C++20新增的4个大特性之一,Mod...

  • C++20:两个极端与概念的救赎

    原文详见:C++20: Two Extremes and the Rescue with Concepts 我们在...

  • C++20学习:基于Ubuntu系统编译gcc10.2.0

    问题 c++20标准已经发布,c++20有比较多的新特性。想尝个先,虽然目前还没有一个编译器能够完全支持c++20...

  • C++雾中风景18:C++20, 从concept开始

    转眼间,C++20的标准已经发布快两年了。不少C++的开源项目也已经将标准升级到最新的C++20了,笔者也开启了新...

  • C++20

    Big Four:Concept:解决模板Coroutines:解决异步Ranges:STL高级Modules:解...

  • C++20 以 Bazel & Clang 开始

    C++20 如何以 Bazel & Clang 进行构建呢? 本文将介绍: Bazel[https://bazel...

网友评论

      本文标题:C++20 读书笔记(2)

      本文链接:https://www.haomeiwen.com/subject/lboqortx.html