【问题标题】:Integer representation of safely derived pointer安全派生指针的整数表示
【发布时间】:2014-08-07 04:37:40
【问题描述】:

我在第 3.7.4.3/3 节中遇到了以下内容:

整数值是安全派生的整数表示 仅当其类型至少与 std::intptr_tand 一样大时的指针 是以下之一:

[...]

— 加法或按位的结果 操作,其中一个操作数是一个整数表示 安全派生的指针值P,如果该结果由 reinterpret_cast<void*> 将比较等于安全派生的 可从reinterpret_cast<void*>(P) 计算的指针。

好的,让int *P = new int(1); 是一个指针,long p_int = <reinterpret_cast<long>(P); 是他的整数表示。考虑以下代码:

int *P = new int(1); //Safely-derived pointer
long p_int = <reinterpret_cast<long>(P); //Integer representation of safely derived pointer
long new_p_int = p_int + 10; // Result of an additive operation
void *new_P = reinterpret_cast<void*>(new_p_int);
void *P_cpnverting_to_void = reinterpret_cast<void*>(P);
cout << "P converted to void* = " << P_cpnverting_to_void << endl;
cout << "P after result of an additive operation = " << new_P << endl;

demo

规则不明确。结果指针如何比较等于 reinterpret_cast(P)?在应用加法运算后,它们永远不会相等。您能否提供反映规则的实际示例?

【问题讨论】:

    标签: c++ pointers


    【解决方案1】:

    关键点是从reinterpret_cast&lt;void*&gt; 产生的指针必须与安全派生的指针可计算 reinterpret_cast&lt;void*&gt;(P) 比较相等。

    它不必等于reinterpret_cast&lt;void*&gt;(P)

    考虑下面的例子,我们用从reinterpret_cast&lt;void*&gt;(P) 计算的安全派生指针展示相等性。

    #include <iostream>
    #include <stdint.h>
    
    using namespace std;
    
    int main(){
        int *P = new int(1); //Safely-derived pointer
        uint64_t p_int = reinterpret_cast<uint64_t>(P); 
        uint64_t new_p_int = p_int + 10; // Result of an additive operation
        void *new_P = reinterpret_cast<void*>(new_p_int);
        void *P_computed_from_void_star = reinterpret_cast<void*>(P) + 10;
        cout << "P converted to void* = " << P_computed_from_void_star << endl;
        cout << "P after result of an additive operation = " << new_P << endl;
    }
    

    【讨论】:

    • -1。您提供的代码甚至无法编译。演示:coliru.stacked-crooked.com/a/7d484ca7aefa1f5b
    • @St.Antario,那是因为您的在线编译器将警告解释为错误。
    • @St.Antario,尝试对void* 进行算术运算时自然会出现警告,但我展示它只是为了说明您询问的规则。
    • Coliru 使用 gcc 4.9.0
    • @St.Antario,此代码在 gcc 4.8.1 上编译并带有警告。
    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 2020-11-25
    • 2015-11-29
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多