反转指向数据成员的指针

时间:2016-04-07 15:29:46

标签: c++ pointers nullptr member-pointers data-member-pointers

您好我想弄清楚是否合法(通过C ++)标准来计算某个成员的偏移量(为了扭转它)。

class A
{
public:
    int a, b, c, d;
};

template <typename ParentClass, typename T>
ParentClass const * offset_this_pointer(T const * member_ptr, T ParentClass::* offset)
{
    ParentClass const * parent_p = nullptr;
    // we are technically dereferencing a NULL pointer here,
    // but we are not using the result, only taking the address of it
    // This works and yields the desired result in MSVC 2010, gcc 4.9.2 and Solaris10 compilers.
    T const * offset_p = &(parent_p->*offset);

    return reinterpret_cast<ParentClass const *>((uintptr_t)member_ptr - (uintptr_t)(offset_p));
}

int main()
{
    A a;

    assert(&a == offset_this_pointer(&a.b, &A::b)); // passes

    return 0;
}

&(parent_p->*offset) parent_p作为nullptr来进行private static final String API_HOST = "api.yelp.com"; static String DEFAULT_LOCATION = "London"; private static final int SEARCH_LIMIT = 20; private static final String SEARCH_PATH = "/v2/search"; private static final String BUSINESS_PATH = "/v2/business"; request =new OAuthRequest(Verb.GET, "https://" + API_HOST + SEARCH_PATH); request.addOAuthParameter(OAuthConstants.TIMESTAMP, seconds.toString()); request.addHeader(OAuthConstants.TIMESTAMP, seconds.toString()); request.addQuerystringParameter("term", DEFAULT_TERM); request.addQuerystringParameter("location", DEFAULT_LOCATION); request.addQuerystringParameter("limit", String.valueOf(SEARCH_LIMIT)); 是合法的C ++吗?

1 个答案:

答案 0 :(得分:2)

它已经辩论了一段时间没有明显的结果。然而,辩论对实施提供的,标准祝福的offsetof宏来说没有实际意义。