简体   繁体   English

如何使一个函数不使用STL容器参数(类似于空指针)?

[英]How to make a function not to use the STL container parameter (similarly to null pointers)?

I'm sure it was already answered here, but can't find it... Say, a function has a parameter which is a reference to an STL vector. 我确定它已经在这里回答了,但是找不到它。。。说一个函数有一个参数,该参数是对STL向量的引用。 Sometimes the function has to fill out the vector, sometimes it does not. 有时函数必须填写向量,有时则不必。 How can I let the function know when it should not fill out the vector? 当不应该填写向量时,如何让该函数知道? If the parameter was a pointer, then calling the function with null/not-null pointer would do the job. 如果参数是指针,则使用null / not-null指针调用该函数即可。 Is it possible to do the same with references without using pointers or additional parameters? 是否可以在不使用指针或其他参数的情况下对引用执行相同操作?

Added: What If I use the following function call: 补充:如果我使用以下函数调用怎么办:

func( std::vector<int>() );

And function header is: 函数头是:

func( std::vector<int>() &vec )
{...}

When how is it going to work? 它什么时候起作用? I've seen this trick in the real code. 我已经在实际代码中看到了这个技巧。 Does it mean the function still performs an action on the vector, but the caller should not bother about creating a vector in his code? 这是否意味着函数仍然对向量执行操作,但是调用者不应该为在其代码中创建向量而烦恼?

This doesn't necessarily qualify as a best practice, but it can be done. 这不一定符合最佳实践的要求,但是可以做到。 Ordinarily an optional parameter is specified with a pointer instead of a reference. 通常,使用指针而不是引用来指定可选参数。 But you can create a sentinel object that has special meaning to your function. 但是,您可以创建一个对您的功能具有特殊含义的哨兵对象。

static std::vector<MyStuff> MyVecNull;

void MyFunc(std::vector<MyStuff>& vec = MyVecNull)
{
    if (&vec != &MyVecNull)  // only do the following if a vector was passed...
  • You could use two different functions. 您可以使用两种不同的功能。
  • Personally, I prefer using references as a light-weight way to pass a large read-only object, and pointers if I'm going to change the object. 就个人而言,我更喜欢使用引用作为传递大型只读对象的轻量级方法,如果要更改对象,则使用指针。 That way the call has the & right on it to show that we're going to change that object. 这样,调用上带有&权限即可表明我们将要更改该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM