Showing posts with label operators. Show all posts
Showing posts with label operators. Show all posts

Thursday, February 16, 2006

testing memory failure allocation

there is a difference of how the memorey failure is handled in C++.
int *pa = new int[10000];

in the article "The new and delete Operators" the MSDN says:
"Beginning in Visual C++ .NET 2002, the CRT's new function (in libc.lib, libcd.lib, libcmt.lib, libcmtd.lib, msvcrt.lib, and msvcrtd.lib) will continue to return NULL if memory allocation fails. However, the new function in the Standard C++ Library (in libcp.lib, libcpd.lib, libcpmt.lib, libcpmtd.lib, msvcprt.lib, and msvcprtd.lib) will support the behavior specified in the C++ standard, which is to throw a std::bad_alloc exception if the memory allocation fails."

hence is vital to know which one you are using.
"Normally, if you #include one of the C++ standard headers, like , you'll get a /defaultlib directive in your object that will reference the appropriate C++ Standard Library according to the CRT model you used (the /M* compiler options). Generally, that will cause the linker to use the throwing operator new from the C++ Standard Library instead of the nonthrowing one from the main CRT, because the order of defaultlib directives will cause libcp.lib to be searched before libc.lib (under /ML)."

hence if you have the following code:

int *pn = new int[1000];

if(pn)
{
// ok, pn is valid
}


the testing is valid only if you use the CRT new and not when you use the std::new. with the std::new this is not valid, it will throw an exception (i am not sure what will pn point to).

Friday, February 03, 2006

subtle difference when using const_cast

ive just read this article: http://www.devx.com/tips/Tip/5508 which shows the subtle difference (when is good \ bad) when using the const_cast on objects.

thinking from the point of view of what a variable may contain (its value) and where this value is stored in computer memory, you can think of 2 kinds of const'ness:

a 'true const':

const int cn = 5; // true const variable; it might be stored in computer ROM

and a 'contractual const':

int num = 0;

const int * pci = # // *pci is a contractual const int

if you try to remove the constness of a variable in order to modify its value, its good to know wheater that variable is a 'true' or 'contractual' const.

modifing a 'true' const variable is undefined (and not desirable to do).

the idea is that a pointer to a const variable is still (just) a pointer containig the address of a variable.

that variable, if you know that its not a true const (like const int num = 0) you can modify it safely.

in other words, 'const' can be more than just 'don't change the value', more then a specifier. it might have implications of how the variable is kept in memory.