简体   繁体   English

用const char *参数类型调用函数的C ++最佳方法

[英]c++ best way to call function with const char* parameter type

what is the best way to call a function with the following declaration 用以下声明调用函数的最佳方法是什么

string Extract(const char* pattern,const char* input);

i use 我用

string str=Extract("something","input text");

is there a problem with this usage 这种用法有问题吗

should i use the following 我应该使用以下

char pattern[]="something";
char input[]="input";
//or use pointers with new operator and copy then free?

the both works but i like the first one but i want to know the best practice. 两者都可以,但是我喜欢第一个,但是我想知道最佳实践。

文字字符串(例如"something" )可以很好地用作函数调用的const char*参数。

Unless you plain to have duplicates of the same strings, or alter those strings, I'm a fan of the first way (passing the literals directly), it means less dotting about code to find what the parameters actually are, it also means less work in passing parameters. 除非您简单地拥有相同字符串的重复项或更改这些字符串,否则我是第一种方式(直接传递文字)的拥护者,这意味着对代码寻找实际参数的兴趣减少了,这也意味着减少了通过传递参数来工作。

Seeing as this is tagged for C++, passing the literals directly allows you to easily switch the function parameters to std::string with little effort. 看到这是为C ++标记的,直接传递文字可以让您轻松地将函数参数切换到std::string

The first method, ie passing them literally in, is usually preferable. 通常最好采用第一种方法,即按字面值传递它们。

There are occasions though where you don't want your strings hard-coded into the text. 在某些情况下,您不希望将字符串硬编码到文本中。 In some ways you can say that, a bit like magic numbers, they are magic words / phrases. 在某些方面,您可以说,就像魔术数字一样,它们是魔术词/短语。 So you prefer to use constant identifier to store the values and pass those in instead. 因此,您更喜欢使用常量标识符来存储值并将其传递给它们。

This would happen often when: 这通常在以下情况下发生:

  • 1 . 1 a word has a special meaning, and is passed in many times in the code to have that meaning. 单词具有特殊含义,并且在代码中多次传递以具有该含义。

or 要么

  • 2 . 2 the word may be cryptic in some way and a constant identifier may be more descriptive 该单词可能以某种方式是神秘的,而常量标识符可能更具描述性

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

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