gpt4 book ai didi

c++ - 内联变量的多次销毁

转载 作者:行者123 更新时间:2023-12-04 17:23:32 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





inline variable is initialized more than once

(3 个回答)


1年前关闭。




这是一个包含内联变量的头文件:

// inline.hpp
#pragma once

#include <iostream>

struct Test {
~Test() { std::cout << "deleted" << std::endl; }
};

inline const Test test;

...分为两个 .cpp文件:

// usage.cpp
#include "inline.hpp"

// main.cpp
#include "inline.hpp"
auto main() -> int { return 0; }

该程序打印“已删除”两次,这是出乎意料的。
我认为每个内联变量只有一个实例,所以我期望只有一个“删除”。

这是编译器的错误吗?还是我做错了什么?

代码是用VS2017编译的。

最佳答案

Is this a bug of compiler?



据我所知,是的。 GCC 和 Clang(以及根据评论的 VS2019)仅打印“已删除”一次。

命名空间范围内的非 volatile const 内联变量具有外部链接。您描述的行为似乎暗示了内部链接,这是编译器的错误行为。

为完整起见,相关标准规则(来自最新草案,我添加的重点,我添加的括号中的强调部分):

[basic.link]

A name having namespace scope has internal linkage if it is the name of

  • ... explicitly declared static; [does not apply] or

  • a non-template variable of non-volatile const-qualified type, [applies...] unless

    • ...
    • it is inline or exported, [exception applies] or

... A name having namespace scope that has not been given internal linkage above [applies] and that is the name of

  • a variable; [applies] or

  • ...

has its linkage determined as follows:

  • if the enclosing namespace has internal linkage, the name has internal linkage; [does not apply]

  • otherwise, if the declaration of the name is attached to a named module ... [does not apply]

  • otherwise, the name has external linkage. [applies]

关于c++ - 内联变量的多次销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58695780/

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