c++ - 在变量前面添加 : 会给出错误的结果
问题描述
我在比较班级。对于下面的代码
#include <string>
#include <set>
#include <tuple>
#include <cassert>
enum class e : bool
{
positive = true,
negetive = false
};
class A
{
public:
int a;
e e1 : 1;
friend bool operator==(const A&, const A&);
};
bool operator==(const A& lhs, const A& rhs) {
auto tie = [](const A& a1) {
return std::tie(a1.a, a1.e1);
};
auto x1 = tie(lhs);
auto x2 = tie(rhs);
return x1 == x2;
}
int main()
{
A a1;
a1.a = 10;
a1.e1 = e::positive;
A b1;
b1.a = 10;
b1.e1 = e::positive;
assert(a1 == b1);
}
输出是:
a.out: main.cpp:44: int main(): Assertion `a1 == b1' failed.
这是错误的,因为其中两个类是相同的。
但是,如果我将代码行从更改e e1 : 1;
为e e1;
它会给出正确的结果。
首先我想知道 : 在这种情况下是做什么的?为什么添加这个后结果是错误的?
代码可以在这里看到。
提前致谢。
解决方案
这个功能:
auto tie = [](const A& a1) {
return std::tie(a1.a, a1.e1);
};
返回一个std::tuple<int const&, e const &>
。即使tuple
存储的字段是引用的,对于位字段也有一个特殊规则,其中制作了位字段的临时副本,并且引用绑定到该临时。这意味着当您从函数返回时,对位字段的引用是悬空的,当您使用后者的该字段时会导致未定义的行为tuple
。
您可以通过显式指定返回类型来解决此问题:
auto tie = [](const A& a1) -> std::tuple<int, e> {
return std::tie(a1.a, a1.e1);
};
这是一个演示。
或者,您可以返回 atuple
衰减参数类型,并避免悬空问题,如下所示:
auto tie = [](const A& a1) {
return std::make_tuple(a1.a, a1.e1);
};
推荐阅读
- spring - 是否可以远程删除应用程序前端的 cookie?
- python - 如何在 Linux 上升级 Python 的 SQLite3 模块使用的 SQLite 版本?
- typescript - 如何根据查询投影定义类型
- python - 如何在具有属性层次结构的 DSL 查询中添加权重
- mysql - MYSQL:停止 IFNULL 返回 null 的“空”行
- python - 在没有原型和标头的情况下,如何在 Python 中查找嵌入对象的数据类型
- reactjs - 从 React-Table 中的一行获取信息/数据/值
- python - 为 plotly 的 Figure show 方法定义全局配置值
- c++ - 为什么在使用 FFTW 将(2d)IDFT 转换为 DFT 时,频域中的数据会“镜像”?
- service - 使用 PATCH 方法更新 SAP BUSINESS ONE 服务层上的 salesOrderLines 时出现问题