views:

227

answers:

3

1) Can someone explain the following?

void OnCreate(HWND hWnd, const LPCREATESTRUCT lpCreateStruct)
{
   lpCreateStruct->x = 2; // this compiles
}

void OnCreate(HWND hWnd, const CREATESTRUCT * lpCreateStruct)
{
   lpCreateStruct->x = 2; // this does not compile
}

2) Is it faster to pass by pointer or by reference? Or the same?

+2  A: 

Why does the following assign 2 to x when it is const?

It shouldn't, any standard-compliant compiler makes that an error because ms points to a const my_structure.

edit:

With your updated case, its a problem of how typedefs work:

typedef T* TPtr;

void f(const TPtr);
void g(T* const);
void h(const T*);

Both f() and g() are equivalent and take a const pointer to a T, while h() a pointer to a const T.

Georg Fritzsche
yea, i tested myself. the code I posted actually didnt compile so I edited with my own code
Marlon
+5  A: 

const LPCREATESTRUCT expands to CREATESTRUCT* const, i.e. a constant pointer to non-const structure, while const CREATESTRUCT* is a non-constant pointer to constant structure, so the compiler is right.

Nikolai N Fetissov
A: 

Assuming you have some control over the signature of the OnCreate method, I would suggest writing it as follows

void OnCreate(HWND hWnd, CREATESTRUCT& createStruct) 
{ 
   createStruct.x = 2; // this compiles 
}

or, if you don't want to allow modification, then

void OnCreate(HWND hWnd, const CREATESTRUCT& createStruct) 
{ 
   createStruct.x = 2; // this does not compile 
}

In addition to avoiding any confusion about exactly what is const, by using C++ references you've also said in code that the argument "can't" be NULL. (Yes, somebody could write OnCreate(hWnd, *(static_cast<CREATESTRUCT*>(NULL))) to create a null reference).

Dan