小编Seb*_*ann的帖子

在 C++20 中将 uint64_t 类型双关为两个 uint32_t

由于严格的别名规则,将 a 读uint64_t为 2 的代码是 UB:uint32_t

uint64_t v;
uint32_t lower = reinterpret_cast<uint32_t*>(&v)[0];
uint32_t upper = reinterpret_cast<uint32_t*>(&v)[1];
Run Code Online (Sandbox Code Playgroud)

uint64_t同样,由于同样的原因,编写 an 的上下部分的代码是 UB:

uint64_t v;
uint32_t* lower = reinterpret_cast<uint32_t*>(&v);
uint32_t* upper = reinterpret_cast<uint32_t*>(&v) + 1;

*lower = 1;
*upper = 1;
Run Code Online (Sandbox Code Playgroud)

如何在现代 C++20 中以一种安全、干净的方式编写这段代码,并可能使用std::bit_cast

c++ type-punning c++20

7
推荐指数
1
解决办法
1327
查看次数

为什么我们需要 std::nullopt

什么时候我们可以使用统一初始化来轻松地默认构造一个std::optional<T>?

std::optional<T> foo() {
   if (on_error)
      return {};

    // ...
}
Run Code Online (Sandbox Code Playgroud)

以上有什么缺点可以std::nullopt解决吗?

c++ c++17

5
推荐指数
1
解决办法
2158
查看次数

重新声明纯虚函数

我最近遇到了以下类型的代码:

struct A {
    virtual void foo() = 0;
};

struct B : public A {
    virtual void foo() = 0;
};

struct C : public B {
    virtual void foo() override {
    }
};
Run Code Online (Sandbox Code Playgroud)

重新声明纯虚方法有什么目的吗?

更重要的是:这会改变语义吗?即B::foo隐藏A::foo并引入新的 vftable?

如果A::foo实际上不是纯虚拟但提供了一个实现(仍然为我编译),那么在上面的示例中会发生什么?

c++

4
推荐指数
1
解决办法
201
查看次数

constexpr 函数采用 const char*

我使用 MSVC v141 和/std:c++17.

constexpr const char* test(const char* foo) {
    return foo + 1;
}

constexpr const char* bc = test("abc");
Run Code Online (Sandbox Code Playgroud)

编译得很好,而

constexpr const char* test(const char* foo) {
    constexpr auto bar = foo;
    return bar + 1;
}

constexpr const char* bc = test("abc");
Run Code Online (Sandbox Code Playgroud)

失败:

错误 C2131:表达式未计算为常量

失败是由在其生命周期之外读取变量引起的

注意:参见'foo'的用法

这是正确的行为还是 MSVC 中的错误?

c++ constexpr

0
推荐指数
1
解决办法
86
查看次数

标签 统计

c++ ×4

c++17 ×1

c++20 ×1

constexpr ×1

type-punning ×1