Why does CDC :: SelectObject (CFont *) accept a CFont object against a pointer?

    CPaintDC dc(this); 
    CFont font; 
    dc.SelectObject(font);  // why does this build? 

The CDC :: SelectObject function takes a type pointer CFont, but why does this happen with an object being provided? I ran into this problem that the above code is unpredictable and may sometimes crash, but not always.

+6
source share
2 answers

The code in question is valid, sort of. It compiles due to a combination of two things:

dc.SelectObject(font), . (operator HFONT()), HFONT. HGDIOBJ ( HGDIOBJ HFONT typedef'd void*).

, , , :

. , :

CFont* pOldFont = (CFont*) dc.SelectObject(font);

, undefined. dc.SelectObject(font) HGDIOBJ (typedef'd as void*), (CFont*). , , , . , , :

CPaintDC dc(this);
CFont font;
CFont oldFont;
// Transfer ownership of font to the DC, and the previously selected font into oldFont
oldFont.Attach(dc.SelectObject(font.Detach()));

// Use dc

// Transfer ownership back
font.Attach(dc.SelectObject(oldFont.Detach()));

// oldFont goes out of scope; this a no-op since it no longer owns any resources
// font goes out of scope, releasing all resources owned by it
// dc goes out of scope, releasing all resources owned by objects selected into it

, , :

CPaintDC dc(this); 
CFont font; 
CFont* pOldFont = dc.SelectObject(&font);

// Use dc

dc.SelectObject(pOldFont);

, , . , CFont ( API). , , : , , MFC, (, , CGdiObject::FromHandle, SelectObject(CFont*)). MFC.

+8

Indpectable, , :

#include "stdafx.h"
#include <iostream>

class A {
    int a_int = 6;
    char* a_carp = "A derived";
public:
    operator int() { return a_int; }
    operator char*() { return a_carp; }
};

class B : public A {
    float b_float = 5.7;
    char* b_carp = "B Derived";
public:
    operator float() { return b_float; }
    operator char*() { return b_carp; }
};

void Print(char * text)
{
    std::cout << text << std::endl;
}

int main() {
    B b_obj;
    //  long a = b_obj;
    char* c_p = b_obj;

    Print(b_obj);

    return 0;
}

, "B ".

?

, . , .

HFONT(). , , / . , ( ), .

?

, OP. , , , :

CFont* pOldFont = (CFont*) dc.SelectObject(font); 

(CFont*) . HGDIOBJ SelectObject(), HGDIOBJ, CFont *, , .

0

All Articles