C++ 向其他函数传递字符的最佳实践

C++ 向其他函数传递字符的最佳实践,c++,visual-c++,C++,Visual C++,我想将字符串传递给第二个函数,在这里它填充字符数组并返回值。在第一个函数中,我想在第二个函数填充字符串后获取字符串长度 第一步 Planning to pass the character array char data[10]=""; GetData(data); // Here Iam doing memset value to data strlen(data); 第二步 Planning to pass the character pointer char *data;

我想将字符串传递给第二个函数,在这里它填充字符数组并返回值。在第一个函数中,我想在第二个函数填充字符串后获取字符串长度

第一步

 Planning to pass the character array 
 char data[10]="";
 GetData(data); // Here Iam doing memset value to data
 strlen(data);
第二步

 Planning to pass the character pointer 
 char *data;
 GetData(data); // what I should do 
 strlen(data);

有人能建议哪一种是最佳实践吗?理想情况下,字符指针应该由调用者拥有,并且应该负责分配(如果可能,或者被调用者必须代表调用者这样做)和解除分配

char *data = (char *) NULL; //  should initialize to know allocated or not
调用的原型GetData应该是:

void GetData(char *& d); // pointer passed as reference
在GetData中,d应分配为:

d = new char[size]; //size should be appropriately decided including null terminating character
例如,如果您希望存储一个“hello”,那么d应分配为:

d = new char[5+1]; // example
完成后,在调用者中,必须按以下方式解除分配:

if (data) delete [] data;
data = (char *) NULL;

您想使用
std::string
,类似于:

std::string data;
void GetData(std::string& str);

通过非代码> const 允许“代码> GATDATABAS/<代码>更改<代码> STR .< /P> < P> Windows中的“经典”,C兼容方法(VisualC++最常用)是具有缓冲区大小作为参数的函数,并返回复制的数据的大小或长度。例如:

//Inputs:
//  buffer: [out/opt] If not null, write data here.
//  size: [in] Buffer size including null terminator, ignored if buffer is null.
//Outputs:
//  buffer: The data.
//  Return Value: Length of data written to the buffer, without null terminator.
int GetData(char *buffer, size_t bufferSize);
这允许使用空缓冲区调用函数,以获取要分配的长度,分配数据,然后再次调用函数


但是,它不是非常C++,而且容易出错。从语言的角度来看,将指针/引用传递给要分配的指针更好,但在跨越DLL边界时有其缺点,建议DLL分配的任何数据都由同一DLL释放(防止使用普通智能指针)。

在第二个示例中,GetData()通过引用获取指针?您使用了两个不同的C++标记。这强烈建议您应该使用对
std::string
的引用。为什么不让
GetData
返回
std::string
?然后您可以执行
std::string data=getData()。你答案的第一行很容易让人误解。这是“经典”,因为它是C。Windows API是C API。这并不意味着您在Windows上编写的所有代码都必须(甚至应该)是C代码。