簡體   English   中英

我可以使用 C++ 中的成員變量地址獲得 object 的引用嗎?

[英]Can I get reference of an object with address of member variable in C++?

如果我只有 object 的成員變量的地址,是否可以獲得對 object 的引用?

class example{
    public:
        int var;
};


int main(){
    
    example exampleObject;
    
    int* point=&exampleObject.var;
    
    example* objPointer; // can i get objPointer to point to exampleObject only using point
    return 1;
}

我可以在 C++ 中獲取帶有變量地址的 object 的引用嗎?

根據示例代碼,此問題中似乎缺少一個關鍵詞。 您似乎希望使用 object 的成員變量的地址而不是 class 類型的變量來引用 object。

可能是的,但有一些限制。

只有當所討論的 class 是標准布局 class 時才有可能。 在這種情況下,您可以將指向第一個成員的指針重新解釋為指向 class 本身的指針。 然后可以通過指針間接獲取引用:

static_assert(std::is_standard_layout_v<example>);
example* objPointer = reinterpret_cast<example*>(point);
assert(objPointer == &exampleObject); // guaranteed to pass

使用offsetof宏可以獲得基於除第一個成員以外的成員的標准布局 class 的指針,盡管我所看到的實現該想法的所有嘗試都依賴於技術上未定義的行為,或者至少是實現定義的東西.

Here is the implementation from the Linux kernel (not written in C++, but C, which may be more relaxed in what is allowed):

 #define container_of(ptr, type, member) ({ \ const typeof(((type *)0)->member) * __mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); })

typeof不在標准 C++ 中,甚至不在標准 C 中,而是 GNU 語言擴展。 這也使用了一個語句表達式(不要與表達式語句混淆),這是另一個 GNU 擴展。

警告:不要經常這樣做,因為這很容易把事情搞砸

#include <iostream>

class example{
public:
    int var;
};


int main(){

    example exampleObject{15};

    int* point=&exampleObject.var;

    example* objPointer = reinterpret_cast<example*>(point);
    std::cout << objPointer->var;
    return 0;
}

now objPointer will points to the original object, however this works only because of how object are managed, and so because since var is the first property of a class without a base class, its address will be the same of the object, but if you有這樣的東西:

class example{
public:
    int var;
    int var2;
};


int main(){

    example exampleObject{15, 16};

    int* point=&exampleObject.var2;

    example* objPointer = reinterpret_cast<example*>(point);
    std::cout << objPointer->var2;
    return 1;
}

它不起作用,因為var2沒有保存在保存 object 的同一地址中,因為在它之前保存了var

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM