开发者

#define file type

开发者 https://www.devze.com 2023-01-19 05:21 出处:网络
Is #define LBitmap std::list < CBITMAP *> a good practice? Edit: Allright, what can I do开发者_JAVA百科 to convince my boss that this is bad practice?No, its not a good practice to use #def

Is

#define LBitmap std::list < CBITMAP *>

a good practice?

Edit: Allright, what can I do开发者_JAVA百科 to convince my boss that this is bad practice?


No, its not a good practice to use #define in C++.

Its good to use typedef as this has a well defined scope

typedef is scope defined and compiler interprets its definition each time it meet which is not the in case of #define. #define is interpreted as compile time itself.

Here is the MSDN definition of typedef and #define

A typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the type-declaration portion of the declaration

When using DEFINE statements, all instances of that statement are replaced by the value of the statement during a preprocessing phase.

#define LBitmap std::list < CBITMAP *>   // BAD

typedef std::list < CBITMAP *> LBitmap  // GOOD

To convince your Boss

#define CHARPTR char*

CHARPTR a, b;

After preprocessing, that line expands to

char* a, b;

Here, only variable a is of type char * whereas b is simply char

If you use typedef

typedef char* CHARPTR;
CHARPTR a, b;

Here both a and b are both of type char *


No, the use of preprocessor macros (#define) is discouraged in C++. Use a typedef instead:

typedef std::list<CBITMAP *> LBitmap;

Edit: to convince your boss, you can use the pointer trick Pardeep posted, but it's even more fun instructive to introduce a subtle bug using references:

#define FooRef Foo &

struct Bar {
    Foo a, b;
};

void func(Bar &bar)
{
    FooRef a = bar.a, b = bar.b;
    a = some_value;
    b = another_value;
}


#define is just an textual replace and it can lead a few problems, resulting in code that you dont intend to have.
typedef if the right way to give alias names for datatypes etc.

Heres an example where #define fails horribly!

#define CHARPTR_DEFINE char*  
typedef char* CHARPTR_TYPEDEF;
CHARPTR_DEFINE ptr1, ptr2;   --> evaluates to char *ptr1, ptr2;
CHARPTR_TYPEDEF ptr3, ptr4;  -->evaluates to char *ptr3,*ptr4;


No, for defining type aliases, there is a much better facility:

typedef std::list< CBITMAP *> LBitmap;

A #define results in a textual replacement, which can lead to surprising results. typedef on the other hand creates a proper alias for some other type.


No. Its better to use a typedef in this case as:

typedef std::list<CBITMAP*> LBitmap;
0

精彩评论

暂无评论...
验证码 换一张
取 消