首页 > 解决方案 > 如何确保参数仅指向静态存储期间的对象?

问题描述

我想确保给函数的参数指向(或引用)具有静态存储持续时间类的对象。

该解决方案需要在没有编译器特定扩展的情况下使用 C++11。

我在研究过程中发现的最相似的问题是仅限于 C 语言的问题。到目前为止,那里提出的解决方案仅适用于编译器特定的扩展。

我想过使用非类型模板参数来限制指向静态存储持续时间的指针,如下所示:

/** @tparam POINTER must point to an integer with static storage duration
 *          (and linkage [before C++17])
 *  @return value pointed to by template argument */
template<int * POINTER>
int letPassStaticStorageDurationOnly()
{
  return *POINTER;
}

int staticStorageInt = 42; // variable with static storage duration
int* pointerToStaticStorageInt = &staticStorageInt; // pointer to variable 

int main()
{
    int autoStorageInt = -42;
    static int functionStaticInt = -21;

    // error: because 'autoStorageInt' has no linkage
    return letPassStaticStorageDurationOnly<&autoStorageInt>(); // shall fail

    // error: because is a variable, not the address of a variable
    return letPassStaticStorageDurationOnly<pointerToStaticStorageInt>();

    // error [<C++17]: because 'functionStaticInt' has no linkage
    return letPassStaticStorageDurationOnly<&functionStaticInt>();

    return letPassStaticStorageDurationOnly<&staticStorageInt>(); // works
}

不幸的是,这(至少)有以下警告:

如何才能确保赋予函数的参数仅在静态存储期间指向(或引用)对象?最好没有我概述的提案的警告。欢迎根本不同的解决方案!

标签: c++storage-duration

解决方案


推荐阅读