【发布时间】:2013-02-12 19:01:45
【问题描述】:
这基本上是我想做的:
SerialPort::ReadBytes(int32& errcode, Message::string& msg, uint32 num)
{
DWORD numBytesRead = 0;
LPDWORD pNumBytesRead = &numBytesRead;
errcode = 0;
std::unique_ptr <char[]> buff (new char[num]);
// ^^^^ pass this char buffer to the ReadFile function below
if (!ReadFile(m_sp_pointer, // Handle to device
buff, // Receives data from device
num, // num bytes to read (in)
(LPDWORD)pNumBytesRead, // num bytes read (out)
NULL))
{
errcode = GetLastError();
}
if (numBytesRead > 0)
{
return true;
}
return false;
}
我确实知道我没有正确执行此操作,所以我的问题是:我如何正确执行此操作,是否有任何事情使这成为一个坏主意?提前致谢。
编辑:我实际上应该在参数中传入unique_ptr,而不是在本地声明它并传入Message::string& msg。
我最初的尝试是通过引用传递Message::string (std::string),所以这也是一个选项.. 即,根本不使用 unique_ptr。在那种的情况下,我会在本地使用常规的char[],然后将msg 的内容设置为char[] 并返回它。
我不确定哪个会更好,似乎很多回复都推荐vector<char>。 (与使用std::string 非常相似)。
【问题讨论】:
-
我会使用
std::vector<char> buff(num);。
标签: c++ visual-c++ pointers c++11