gpt4 book ai didi

c++ - 将 std::vector 的一部分转换为 std::array, c++11

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:32 30 4
gpt4 key购买 nike

根据 C++11 标准,以下代码是否违反了严格的别名或以其他方式导致未定义的行为?是否有更好的方法来实现相同的功能?

void do_things(const std::array<char, 64> &block) {
// ...
}

int main() {
std::vector<char> buffer(64);
do_things(reinterpret_cast<const std::array<char, 64> &>(buffer[0]));
}

tldr:使用const char *不那么痛苦了

编辑:自 sizeof(std::array<char, n>)不保证等于 n ,然后我提出以下建议:

void do_things(const char (&block)[64]) {
// ...
}

int main() {
std::vector<char> buffer(64);
do_things(reinterpret_cast<char (&)[64]>(buffer[0]));
}

根据我对别名的理解,这不应导致未定义的行为并捕获传递固定大小数组的语义。我的理解正确吗?

最佳答案

严格的别名规则引用§3.10 [basic.lval]/p10,它规定

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar (as defined in 4.4) to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union)
  • [...]

因此,访问类型为 char 的对象通过 std::array<char, N> 类型的左值不违反这条规则,因为std::array<char, N>是一个聚合类型,包括 char作为非静态子聚合数据成员的元素。

但是,由于不同的规则 - §9.3.1 [class.mfct.non-static]/p2:

If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.

同样值得注意的是,标准中没有任何规则保证 sizeof(std::array<T, N>) == sizeof(T) * N .标准唯一保证的是 std::array<T, N>是一种聚合类型,它可以使用包含最多 Nbraced-init-list 进行初始化T秒。该实现可以免费添加额外的东西。

取决于什么do_things需要,你可能想让你的函数接受随机访问迭代器,或者只是一个指针。或者,如果你想限制你的功能只接受 std::vectorstd::array s,你可以编写重载,将 const refs 带到那些,并调用一个辅助函数 const char *完成实际工作。


新版本没有违反我能想到的任何规则,但要求 reinterpret_cast 是相当糟糕的设计几乎每次调用函数时都会使用。如果你不小心声明了 buffer作为std::vector<std::string> , 或写成 buffer而不是 buffer[0] ,编译器会在没有警告的情况下愉快地编译您的代码,这可能会带来灾难性的后果。

关于c++ - 将 std::vector<char> 的一部分转换为 std::array<char, n>, c++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25091602/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com