Void pointers in C ++

I saw this example on a website, and on sites it is mentioned: "One of its uses (void pointers) may be to pass general parameters to a function"

// increaser
#include <iostream>
using namespace std;

void increase (void* data, int psize)
{
  if ( psize == sizeof(char) )
  { char* pchar; pchar=(char*)data; ++(*pchar); }
  else if (psize == sizeof(int) )
  { int* pint; pint=(int*)data; ++(*pint); }
}

int main ()
{
  char a = 'x';
  int b = 1602;
  increase (&a,sizeof(a));
  increase (&b,sizeof(b));
  cout << a << ", " << b << endl;
  return 0;
}

Isn't it easier to write code as shown below?

void increaseChar (char* charData)
{
    ++(*charData);
}

void increaseInt (int* intData)
{
    ++(*intData);
}

int main ()
{
  char a = 'x';
  int b = 1602;
  increaseChar (&a);
  increaseInt (&b);
  cout << a << ", " << b << endl;
  string str;
  cin >> str;
  return 0;
}

This is less code and really simple. And in the first code I had to send the data type size here, I do not!

+5
source share
6 answers

It’s best to make the function type safe and versatile. It would also be better to take an argument by reference instead of a pointer:

template <typename T>
void increment(T& data) {
    ++data;
}

void* should be avoided whenever possible in C ++, since patterns and inheritance provide alternatives to types.

+13
source

. void* , . .

++, , void*. , :

template <class T> T increase(T* value)
{
    return ++(*value);
}

int main(int argc, char* argv[])
{
    int i(0);
    increase<int>(&i);

    char c(0);
    increase<char>(&c);

    return 0;
}

-, ?

0

int char. , (, struct). , ​​ .

0

" ( void) "

, . :

a) (, , ), ,
b) .

increaseInt increaseChar. :

template<typename T>
void increase(T* pData)
{
    ++(*pData);
}

, ++ .


void " " - , pthread. , ( , ), - well-a void*. pthread C ++, , ++, void* " ". ; , .

0

, , . C qsort, void*, , .

++ , .

, void*

  • ,
  • , C.
0

C ( ++), void * - - . , . , void *. :

void handle_crash(void* data)
{
    Log* log = (Log*)data;
    log->print("We crashed.");
}

Log log;
set_crash_handler(&handle_crash, &log);

You will see this often on C-frames such as libxml2 or spidermonkey. In case C, this is the only thing to do. This is not a very reliable solution.

If you work with C ++, you have more options. Basic general programming can be done using templates or overloading as indicated in other answers. If you need a reliable callback mechanic, you can look in libsig ++ or other “signals and slots”.

0
source

All Articles