1

假设我有这个代码。您的基本“如果调用者不提供值,则计算值”场景。

void fun(const char* ptr = NULL)
{
   if (ptr==NULL) {
      // calculate what ptr value should be
   }
   // now handle ptr normally
}

并调用它

fun();          // don't know the value yet, let fun work it out

或者

fun(something); // use this value

然而,事实证明,ptr 可以有各种值,包括 NULL,所以我不能使用 NULL 作为调用者不提供 ptr 的信号。

所以我不确定现在给 ptr 什么默认值而不是 NULL。我可以使用什么魔法值?有人有想法吗?

4

7 回答 7

4
void fun()
{
   // calculate what ptr value should be
   const char* ptr = /*...*/;

   // now handle ptr normally
   fun(ptr);
}
于 2012-05-07T21:15:01.270 回答
2

根据您的平台,指针可能是 32 位或 64 位值。

在这些情况下,请考虑使用:

0xFFFFFFFF or  0xFFFFFFFFFFFFFFFF

但我认为更大的问题是,“如何将 NULL 作为有效参数传递?”

我建议改为使用另一个参数:

void fun(bool isValidPtr, const char* ptr = NULL)

或者可能:

void fun( /*enum*/ ptrState, const char* ptr = NULL)
于 2012-05-07T21:16:37.683 回答
2

我同意提供的所有其他答案,但这是另一种处理方式,对我个人来说,如果更冗长,它看起来更明确:

void fun()
{
  // Handle no pointer passed
}

void fun(const char* ptr)
{
  // Handle non-nullptr and nullptr separately
}
于 2012-05-07T21:29:23.553 回答
1

对不同的输入使用相同函数的重载版本是最好的,但如果你想使用单个函数,你可以将参数设置为指针指向指针:

void fun(const char** ptr = NULL) 
{ 
   if (ptr==NULL) { 
      // calculate what ptr value should be 
   } 
   // now handle ptr normally 
} 

然后你可以这样称呼它:

fun();

.

char *ptr = ...; // can be NULL
fun(&ptr);
于 2012-05-08T01:16:50.340 回答
1

您应该为此使用 nullptr 。它在 C++11 标准中是新的。在这里查看一些解释。

于 2012-05-07T21:15:29.617 回答
1

如果您想要一个与没有用的参数相对应的特殊值,请创建一个。

头文件:

extern const char special_value;

void fun(const char* ptr=&special_value);

执行:

const char special_value;

void fun(const char* ptr)
{
    if (ptr == &special_value) ....
}
于 2012-05-08T02:42:51.487 回答
0

1?

我无法想象有人用那个地址分配你的内存。

于 2012-05-07T21:14:40.300 回答