Showing posts with label STL. Show all posts
Showing posts with label STL. Show all posts

Tuesday, March 18, 2008

Alias can be a tricky problem in C++'s STL vector

(Mar 14, 2008)

Alias can be a tricky problem in C++'s STL vector.

Sometimes, I don't want to write an awkward code such as willFail.m_vecProblematic[0] all the time, so I create an alias (prob1 in this example). This alias will work fine until we push or pop elements in a vector to a certain number and the vector is needed to reallocate.

Problematic* prob1 = &( willFail.m_vecProblematic[0] );
prob1->m_vec2.push_back( 55 );
prob1->m_vec1.push_back( 11111 );

// Push an element to a vector may cause a vector to reallocate.
willFail.m_vecProblematic.push_back( Problematic );

// prob1 may not point to a correct storage, but this value assignment

// may not cause a program to crash instantly.
prob1->i = 24;

// prob1 may not point to a correct storage, and such object

// operation usually cause a program to crash
prob1->m_vec2.push_back( 66 );

Note: simple value assignment to an invalid place may not cause a program to crash so easily, but calling a method from an invalid object pointer will cause a program to crash very easily since the method table of an object is already messed up. If we want to find where a program goes wrong, we may try to call a method of a suspecious object pointer.

Monday, April 16, 2007

valarray problem in Visual Studio

(Apr 16, 2007)

I tried to use valarray in Visual Studio and got some compile errors and warnings:
"warning C4003: not enough actual parameters for macro 'min'
warning C4003: not enough actual parameters for macro 'max'

error C2059: syntax error : ')'
c:\Program Files (x86)\Microsoft Visual Studio .NET 2003\Vc7\include\valarray(427) : see reference to class template instantiation 'std::valarray<_ty>' being compiled

error C2334: unexpected token(s) preceding ':'; skipping apparent function body
...
"

These problem will occur only when we try to use statically linked MFC library. In http://www.codeguru.com/forum/archive/index.php/t-342787.html, Paul suggested that we need to make sure that valarray is included before afx stuff. This is because MS implements min and max macro and defines them in afx pre-compile header file. Any class that has min and max will have this problem.

However, if I switch the order, it seems that all declaration of valarray will be removed and I just got other compiler errors. It seems that the solution from Paul could not work for my situation.

After trying for a while, I finally decided to rename valarray.h to valarray_mod.h and change the function names from min and max to minimum and maximum instead.