在命名空间中定义变量但在测试中得到空值

Define variable in namespace but get null value in test

我有个C++问题想请教。

在header中,我定义了一个结构如下:

struct ObjectType
{
    const int                                 id;
    const std::string&                        value;

    ObjectType(const int id, const std::string& value = ""):
                    id     (id)
                  , value  (value)
{

}

};

在匿名命名空间中,我定义了三个变量:

namespace {
    const ObjectType sample1   (0, "sample1");
    const ObjectType sample2   (1, "sample2");
    const ObjectType sample3   (2, "sample3");
}

然后在我的单元测试中,当我尝试使用 ObjectType 时,该值始终为 NULL:

TEST(TestClass, test01)
{
   std::cout << sample1.value << std::endl; // => This is always empty
}

我记得自从我将结构字段定义为 const 后,它应该会延长输入的生命周期。然后应该打印 sample1.value 。然而它没有.. 任何人都知道为什么会发生?谢谢!

这是未定义的行为。

const ObjectType sample1   (0, "sample1");

因为这个 class 的构造函数的参数是一个 const std::string &,它从字符串文字构造一个临时的 std::string 对象,将它传递给构造函数,并且当构造函数 returns 临时对象被销毁。

构造函数将对临时对象的引用保存为其 class 成员。不幸的是,临时对象在稍后被引用之前被销毁,导致未定义的行为。

这与名称空间无关。