可以将未初始化字段的对象安全地添加到 std::vector 中吗?

问题描述 投票:0回答:1

在下面的程序中,结构体

A
的默认构造函数不会初始化其字段
v
。然后在常量表达式中,
std::vector<A>
被放置为
A()
对象:

#include <vector>

struct A {
  constexpr A() noexcept {}
  int v;
};

constexpr bool f() {
    std::vector<A> as;
    as.reserve(1);
    as.emplace_back();
    return true;
}
static_assert( f() );

MSVC 编译器抱怨读取未初始化的变量:

<source>(14): error C2131: expression did not evaluate to a constant
<source>(11): note: failure was caused by a read of an uninitialized symbol
<source>(11): note: see usage of 'A::v'
c++ vector language-lawyer constexpr
1个回答
0
投票

看起来 MSVC 正确报告了读取错误。

问题不在于向量中的分配,而是

emplace_back()
是一个返回表达式的方法,即对添加元素的引用。

这也可以从下面的内容中看出,它创建了一个 A 对象,提供了对它的引用,然后,当评估该引用时会导致错误。

struct A {
    constexpr A() noexcept {}
    int v;
};

constexpr bool f() {
    A a;
    A& b = a;
    // b;   // uncommenting this causes MSVC to fail
    return true;
}
static_assert(f());

int main() {}

编译正常,但如果

b
,对对象的引用进行评估,则会出现错误:

Message     failure was caused by a read of an uninitialized symbol 
© www.soinside.com 2019 - 2024. All rights reserved.