Is it possible to pass string from the string class as a pointer to function?

0

Is it possible to pass string from string class as pointer to function?

example:

void separaStr(string *modulo, satring *nmodulo, *digito){}
    
asked by anonymous 25.09.2015 / 21:06

1 answer

1

I assume you are asking if it is possible to move to a function, a pointer to a std :: string.

Yes, it is possible. The signature of the function would be, for example:

int funcao(std::string *str)

However, as a rule, it suggested that whenever the function argument is required (it can not be null ) and if the function does not save a pointer or otherwise change the ownership / ownership of the argument, you override the use of a pointer by the use of a reference.

The use of the reference allows, as with the pointer, to change the value of the string and in terms of syntax the difference in the use of the parameter would be

str.membro (str é uma referência)

instead of

str->membro (str é um apontador)
One of the benefits of using a reference is the fact that the reference clearly expresses the condition that the function parameter can not be null.

In a larger project this can, for example, help you easily identify points in the code where you need to check if the argument is null and the cases where doing this validation is unnecessary.

The signature of the function that receives a string passed by reference would be:

int funcao(std::string &str)

or

int funcao(const std::string &str)

for cases where the parameter is not changed in the function.

A maxim that I try to follow whenever programming in C ++ is:

  • Uses a reference whenever possible and a pointer only where strictly necessary.
26.09.2015 / 09:32