首页 > 解决方案 > 内联和外联,这个例子相似吗?

问题描述

示例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++global-variablesinlineexternlinkage

解决方案


推荐阅读