【发布时间】:2018-09-26 19:01:24
【问题描述】:
我有一个导出 char* 的库,我可以在其中生成一条消息,然后调用 send 来发送消息(通过网络)。如何在代码中向导出的缓冲区写入非常简单的消息?
我写了四种不同的方法来写消息,没有一个是理想的:
class Lib {
char msg[100];
public:
Lib() {
// nullify the buffer
msg[0] = 0;
}
char* get_buffer() {
return msg;
}
void send() {
std::cout << "Message is: " << msg << std::endl;
// nullify the buffer for the next send
msg[0] = 0;
}
};
int main () {
{
Lib lib;
char* buf = lib.get_buffer();
// Method 1 is tedious
buf[0] = 'H';
buf[1] = 'e';
buf[2] = 'l';
buf[3] = 'l';
buf[4] = 'o';
buf[5] = 0;
lib.send();
}
{
Lib lib;
char* buf = lib.get_buffer();
// Method 2 doesn't work
buf = "Hello";
lib.send();
}
{
Lib lib;
char* buf = lib.get_buffer();
// Method 3 involves a copy
string str = "Hello";
str.copy(buf, str.size());
lib.send();
}
{
Lib lib;
char* buf = lib.get_buffer();
// Method 4 involves a copy
char* c_arr = "Hello";
std::memcpy(buf, c_arr, 6);
lib.send();
}
}
输出是:
Message is: Hello
Message is:
Message is: Hello
Message is: Hello
第一种方法对我来说似乎很乏味。第二种方法不起作用,因为buf 然后指向内存中包含“Hello”的新位置。第三种和第四种方法涉及创建临时内存缓冲区和内存副本。
我想要类似于 buf = {'H', 'e', 'l', 'l','o'}; 的东西,但这仅在构建时有效。
更不用说我在方法 2 和方法 4 中都有一个编译警告,g++-7.3:
warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
【问题讨论】:
-
您的警告是说您正在将字符串文字转换为
char*。这是 c++ 不再支持的东西。他们应该只分配给const char*。 -
最简单的解决方案是让
Lib::msg成为std::string。 -
char* send()你没有从那个方法返回任何东西 -
抱歉,改成
void send()。 -
给你一个缓冲区。您将不得不在某些时候将数据复制到其中以使缓冲区有用。