简体   繁体   English

将空字符串作为参数传递给函数

[英]Passing null string to function as an argument

What is the right way of passing NULL string to a function without creating a variable?在不创建变量的情况下将 NULL 字符串传递给函数的正确方法是什么? I see compilation error with following code and I don't want to change the definition.我看到以下代码出现编译错误,我不想更改定义。 Also may have to make change to string so don't want to mark it a constant type.也可能必须对字符串进行更改,因此不想将其标记为常量类型。

#include <iostream>
#include <string>

using namespace std;
void
myfunc(int i,  string &my) {
   if (my.empty()) {
      cout << "Empty" << endl;
   } else {
      cout << "String is " << my <<endl;
   }
}
int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  std::string str2 ("");
  myfunc(2, "");
  return 0;
}`

my1.cpp:18: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'const char*' my1.cpp:6: error: in passing argument 2 of 'void myfunc(int, std::string&) ' my1.cpp:18:错误:从“const char *”类型的临时变量中对“std::string&”类型的非常量引用无效初始化 my1.cpp:6:错误:在传递“void myfunc”的参数 2( int, std::string&) '

Following compiles but I dont want to create local variable以下编译但我不想创建局部变量

#include <iostream>
#include <string>

using namespace std;
void
myfunc(int i,  string &my) {
   if (my.empty()) {
      cout << "Empty" << endl;
   } else {
      cout << "String is " << my <<endl;
   }
}
int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  std::string str2 ("");
  myfunc(2, str2);
  return 0;
} 

The solution here is to have an overload that doesn't have the string parameter. 此处的解决方案是使重载没有字符串参数。

void myfunc(int i,  string &my) {
      cout << "String is " << my <<endl;
}

void myfunc(int i) {
   cout << "Empty" << endl;
}

int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  myfunc(2);
}

This is the most simple and clear solution that conveys exactly your intent and functionality. 这是最简单,最清晰的解决方案,可以准确传达您的意图和功能。

You shouldn't try to do it your way because if you want to modify the argument then the parameter should be "non-const reference" and so it cannot bind to temporaries. 您不应该尝试按照自己的方式进行操作,因为如果要修改参数,则参数应为“非常量引用”,因此它不能绑定到临时变量。 Thus you can't pass a string literal to it. 因此,您不能将字符串文字传递给它。


If you want to make it explicit that you don't pass a string, you could create a tag ala nullptr , although I do not recommend the extra complication when the above variant is clear and understood by everybody at first glance. 如果您想明确表示您不传递字符串,则可以创建一个标签ala nullptr ,尽管当上述变体清晰易懂且每个人都乍看之下时,我不建议这样做。

struct no_string_tag_t {};
constexpr no_string_tag_t no_string_tag;

void myfunc(int i,  string &my) {
      cout << "String is " << my <<endl;
}

void myfunc(int i, no_string_tag_t) {
   cout << "Empty" << endl;
}

int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  myfunc(2, no_string_tag);
}

If you really want a single function, then the semantically correct version would have an optional reference. 如果您确实需要单个功能,则语义正确的版本将具有可选的引用。

auto foo(int i, std::optional<std::reference_wrapper<std::string>> my)
{
    if (my)
        cout << "String is " << my <<endl;
    else
        cout << "no string" << endl;

}
int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  myfunc(2, std::nullopt);
}

If you want to keep the function signature and still be able to pass it a temporary, then you are out of luck. 如果您想保留功能签名并且仍然能够暂时传递它,那么您就不走运了。 C++ has a safety feature in that it does not allow a non-const lreferece to bind to a temporary. C++具有安全功能,因为它不允许非常量首选项绑定到临时文件。 The reason for this restriction is that attempting to modify a temporary via a lreference would most likely be bug and not the programmers's intent since the temporary dies out anyway. 这种限制的原因是,通过临时引用尝试修改临时文件很可能是错误,而不是程序员的意图,因为临时文件无论如何都会消失。

You can't pass a temporary to a non-const reference parameter. 您不能将临时变量传递给非常量引用参数。 The object, being temporary, will be destroyed as soon as the function returns. 函数返回后,作为临时对象的对象将被销毁。 Any changes that the function did to the object would be lost. 函数对对象所做的任何更改都将丢失。

If you want to have the chance to modify the string, you can take the string by const reference and return a modified string. 如果您希望有机会修改字符串,则可以通过const引用获取字符串并返回修改后的字符串。

string myfunc( int i, string const &s );
:
str1 = myfunc( 1, str1 );
auto result2 = myfunc( 2, "" );

Your other option is to use a pointer to a string that can be null. 您的另一个选择是使用指向可以为空的字符串的指针。

void myfunc( int i, string *s ) {
    if (!s) {
        cout << "Empty" << endl;
    } else {
        cout << "String is " << *s <<endl;
    }
}

myfunc( 1, &str1 );
myfunc( 2, nullptr );

You can ommit 1 or more arguments in functions calls as long those argument(s) are the last ones in the order or the args prototyped in that function.您可以在函数调用中省略 1 个或多个参数,只要这些参数是顺序中的最后一个参数或该函数中原型化的参数。

You can also give a padron value if the argument is ommited when calling the function.如果在调用函数时省略了参数,您也可以给出 padron 值。

using namespace std;

void sTest(int a, string x ="TEST", int z=0);

void sTest(int a, string x, int z)
 {
    cout << x;

 }

int main() 
{   
   sTest(5); // displayed “TEST”
}

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

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