C ++标准:命名空间范围的constexpr变量是否具有内部链接? [英] C++ standard: do namespace-scoped constexpr variables have internal linkage?

查看:113
本文介绍了C ++标准:命名空间范围的constexpr变量是否具有内部链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个标头foo.h,其中包含以下内容:

Imagine we have a header foo.h containing the following:

#ifndef FOO_H_
#define FOO_H_

namespace foo {
constexpr std::string_view kSomeString = "blah";
}

#endif  // FOO_H_

foo::kSomeString是否可以确保在包含foo.h的任何翻译单元中具有内部链接?这在C ++ 11和C ++ 17之间是否有所不同?

Is foo::kSomeString guaranteed to have internal linkage in any translation unit that includes foo.h? Does this vary between C++11 and C++17?

在标准草案 [basic.link]/3 中说

[...]具有名称空间范围的名称是内部链接,如果它是既不显式声明为extern也不事先声明为具有外部链接[]的非常量常量限定类型的非内联变量的名称. ..]

A name having namespace scope has internal linkage if it is the name of [...] a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage [...]

但是我不知道constexpr是否算作"const限定符".标准在某处这样说吗?

But I don't know if constexpr counts as "const-qualified". Does the standard say so somewhere?

假设这保证具有内部链接,那么对于这种用法,ODR似乎没有问题,对吗? (与此答案中的内容相反.)

Assuming this is guaranteed to have internal linkage, it seems like there can be no problem with the ODR for this usage, right? (In contrast to what it says in this answer.)

推荐答案

是的,对象声明上的constexpr表示该对象为const.参见 [dcl.constexpr]/9 .是的,这意味着您的示例中的kSomeString具有内部链接.

Yes, constexpr on an object declaration means that the object is const. See [dcl.constexpr]/9. And yes, that means that kSomeString in your example has internal linkage.

我们在这里谈论的违反ODR的种类不是kSomeString本身的定义,而是尝试使用它的其他定义.正是由于内部链接,才出现了一个问题.考虑:

The species of ODR violation we are talking about here is not the definition of kSomeString itself, but other definitions that attempt to use it. And there's a problem precisely because of the internal linkage. Consider:

void f(const std::string_view &);

inline void g() { 
    f(foo::kSomeString); 
}

如果包含在多个翻译单元中,则这违反了ODR,这主要是因为每个翻译单元中的g的定义都引用了一个不同的对象.

This is an ODR violation if included in multiple translation units, essentially because the definition of g in each translation unit references a different object.

这篇关于C ++标准:命名空间范围的constexpr变量是否具有内部链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆