c++ - C++ 中的空指针

标签 c++

我在网站上看到这个例子,网站提到:- “它的用途之一(空指针)可能是将泛型参数传递给函数”

// 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;
}

像下面这样写代码不是更简单吗?

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;
}

它的代码更少,而且非常简单。在第一个代码中,我必须在这里发送数据类型的大小,但我没有!

最佳答案

最好使函数类型安全且通用。最好通过引用而不是指针来获取参数:

template <typename T>
void increment(T& data) {
    ++data;
}
在 C++ 中应尽可能避免

void*,因为模板和继承提供了类型安全的替代方案。

关于c++ - C++ 中的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4304940/

相关文章:

c++ - 在VS2008编译的MFC App中关闭XP Theme

c# - 套接字消息头构建

C++:从 pthread 调用 sendmail 导致 Broken Pipe

c++ - 字符数组初始化和尾随 null

c++ - 强制操作系统在 "subroutine"之后执行清理

c++ - test.exe 中 0x76C9FD62 处的错误未处理异常:Microsoft C++ 异常:内存位置 0x006FF870 处的 std::out_of_range。发生

c++ - 提供非常量引用 getter 是否有意义

c++ - C++ 的 VTK 和 ITK

c++ - 需要澄清类的虚函数和私有(private)成员

c++ - Boost Asio 异步 : Server sent message to client