2 quick questions about passing by const pointer/const reference
1) Can someone explain the following?
void OnCreate(HWND hWnd, con开发者_如何转开发st 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?
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.
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
.
精彩评论