我已经多次阅读了新的 c++20 特性no_unique_address
,我希望有人能用一个比下面这个来自 c++ 参考的例子更好的例子来解释和说明。
说明 适用于在非位域的非静态数据成员的声明中声明的名称。
指示此数据成员不需要具有与其类的所有其他非静态数据成员不同的地址。这意味着如果成员具有空类型(例如无状态分配器),编译器可能会优化它以不占用空间,就像它是一个空基一样。如果该成员不为空,则其中的任何尾部填充也可以重新用于存储其他数据成员。
#include <iostream>
struct Empty {}; // empty class
struct X {
int i;
Empty e;
};
struct Y {
int i;
[[no_unique_address]] Empty e;
};
struct Z {
char c;
[[no_unique_address]] Empty e1, e2;
};
struct W {
char c[2];
[[no_unique_address]] Empty e1, e2;
};
int main()
{
// e1 and e2 cannot share the same address because they have the
// same type, even though they are marked with …
Run Code Online (Sandbox Code Playgroud) 我正在尝试加快我的 C 程序的速度,以便更快地输出数据。
目前我正在用来printf()
向外界提供一些数据。它是连续的数据流,因此我无法使用 return(data)。
我如何使用write()
或fwrite()
将数据提供给console
而不是文件?
总的来说,我的设置由用 C 编写的程序组成,其输出发送到 python 脚本,在其中进一步处理数据。我形成一个管道:
./program_in_c | script_in_python
Run Code Online (Sandbox Code Playgroud)
通过使用更多处理器核心,这为 Raspberry Pi 带来了额外的好处。
我在下面有这个私有成员函数,(类模板的一部分,Heap
):
template <typename Task, typename Priority>
const size_t& Heap<Task, Priority>::parent_of(const size_t& index) const
{
// ** warning C4172: returning address of local variable or temporary
return (this_index-1)/2;
}
Run Code Online (Sandbox Code Playgroud)
我从其他函数调用它,如下所示:
template <typename Task, typename Priority>
void Heap<Task, Priority>::bubble_up(const size_t& start_index)
{
....
if (priority_of(start_index) > priority_of((parent_of(start_index))))
{
... do work ...
//call recursively the bubble_up
bubble_up(parent_of(start_index));
}
...
}
Run Code Online (Sandbox Code Playgroud)
问题是,priority_of
函数参数index
在递归的第二次调用中被破坏或释放:
template <typename Task, typename Priority>
const Priority& Heap<Task, Priority>::priority_of(const size_t& index) const
{
return vec.at(index).second; …
Run Code Online (Sandbox Code Playgroud) 我来自 c++98,我正在尝试进入 c++11 等等。我遇到了公共成员函数 , std::exception::what
, <=>virtual const char* what() const noexcept;
从这个例子中给出的c++参考:what_example,我可以理解用法,但我有几个问题:
// exception::what
#include <iostream> // std::cout
#include <exception> // std::exception
struct ooops : std::exception {
const char* what() const noexcept {return "Ooops!\n";}
};
int main () {
try {
throw ooops();
} catch (std::exception& ex) {
std::cout << ex.what();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
virtual const char* what() const throw();
,在 c++11 中,它变成virtual const char* what() const noexcept; …