c++ - 内联和外联,这个例子相似吗?
问题描述
示例1:使用在bodyinline
中声明和定义非const
static
成员变量。class
这两个示例是否会在多个翻译单元中执行相同/具有相同结果?
#include <iostream>
#include <vector>
struct A1 {
static int counter;
// The vector's here to try something with a default constructor
static std::vector<int> vec;
A1() {
++counter;
vec.push_back(counter);
}
~A1() {
--counter;
vec.push_back(counter);
}
};
int A1::counter = 0;
std::vector<int> A1::vec;
// Will this work as intended across multiple files?
// This one looks more elegant, I don't need to define them outside the class
struct A2 {
inline static int counter = 0;
inline static std::vector<int> vec;
A2() {
++counter;
vec.push_back(counter);
}
~A2() {
--counter;
vec.push_back(counter);
}
};
int
main() {
A1 a11;
A1 a12;
std::cout << A1::counter << '\n';
std::cout << A1::vec.back() << '\n';
A2 a21;
A2 a22;
std::cout << A2::counter << '\n';
std::cout << A2::vec.back() << '\n';
return 0;
}
示例 2:使用inline
而不是extern
来声明和定义一个非constexpr
const
thread_local
全局的。
同样,这两个示例是否会在多个翻译单元中执行相同/具有相同结果?
第一个选项:
// A.hpp
auto
get_thread_seed() {
// Just a silly example
int * value = new int();
auto const seed = reinterpret_cast<uintptr_t>(value);
delete value;
return seed;
}
extern thread_local auto const thread_seed;
// A.cpp
#include <A.hpp>
extern thread_local auto const thread_seed = get_thread_seed();
第二种选择:
// A.hpp
auto
get_thread_seed() {
// Just a silly example
int * value = new int();
auto const seed = reinterpret_cast<uintptr_t>(value);
delete value;
return seed;
}
inline thread_local auto const thread_seed = get_thread_seed();
所有这些在ODR
使用方面都一样吗?
解决方案
推荐阅读
- c# - 带有 Azure OAuth 的 ASP.NET Core MVC 在入口后进入无限登录循环
- matlab - bwboundaries 和轴 - Matlab
- javascript - 使用firebase在快照forEach之后调用一个函数
- javascript - 在接受数字或数组作为参数的函数内部,如何有效地操作这些参数而不管类型如何?
- javascript - 博览会永无止境,不断闪烁下载 java-script 包
- python - 如何从表单检索数据到视图
- sql - 我的查询有问题,我不知道是什么问题?
- angular - Angular - 路由路径抛出控制台错误
- python - Mask R-CNN 中的预训练权重和初始化权重是什么?
- php - 尝试通过 CURL 发送消息后未经授权的 Discord 响应