gpt4 book ai didi

c++ - TCHAR 数组的深拷贝被截断

转载 作者:行者123 更新时间:2023-11-30 02:42:40 27 4
gpt4 key购买 nike

我创建了一个类来测试我需要使用的一些功能。本质上,该类将获取传入字符串的深层拷贝,并通过 getter 使其可用。我正在使用 Visual Studio 2012。在项目设置中启用了 Unicode。

问题是 memcpy 操作产生了截断的字符串。输出是这样的;

THISISATEST: InstanceDataConstructor: Testing testing 123
Testing te_READY

其中第一行是对传入的 TCHAR* 字符串的检查,第二行是使用 memcpy 操作填充分配的内存的输出。预期输出是; “测试测试123”。

谁能解释一下这里出了什么问题?

注意从这里得到#ifndef UNICODE typedefs:how-to-convert-tchar-array-to-stdstring

#ifndef INSTANCE_DATA_H//if not defined already
#define INSTANCE_DATA_H//then define it

#include <string>

//TCHAR is just a typedef, that depending on your compilation configuration, either defaults to char or wchar.
//Standard Template Library supports both ASCII (with std::string) and wide character sets (with std::wstring).
//All you need to do is to typedef String as either std::string or std::wstring depending on your compilation configuration.
//To maintain flexibility you can use the following code:
#ifndef UNICODE
typedef std::string String;
#else
typedef std::wstring String;
#endif
//Now you may use String in your code and let the compiler handle the nasty parts. String will now have constructors that lets you convert TCHAR to std::string or std::wstring.


class InstanceData
{
public:
InstanceData(TCHAR* strIn) : strMessage(strIn)//constructor
{
//Check to passed in string
String outMsg(L"THISISATEST: InstanceDataConstructor: ");//L for wide character string literal
outMsg += strMessage;//concatenate message
const wchar_t* finalMsg = outMsg.c_str();//prepare for outputting
OutputDebugStringW(finalMsg);//print the message

//Prepare TCHAR dynamic array. Deep copy.
charArrayPtr = new TCHAR[strMessage.size() +1];
charArrayPtr[strMessage.size()] = 0;//null terminate
std::memcpy(charArrayPtr, strMessage.data(), strMessage.size());//copy characters from array pointed to by the passed in TCHAR*.

OutputDebugStringW(charArrayPtr);//print the copied message to check
}

~InstanceData()//destructor
{
delete[] charArrayPtr;
}

//Getter
TCHAR* getMessage() const
{
return charArrayPtr;
}

private:
TCHAR* charArrayPtr;
String strMessage;//is used to conveniently ascertain the length of the passed in underlying TCHAR array.
};
#endif//header guard

最佳答案

没有所有动态分配内存的解决方案。

#include <tchar.h>
#include <vector>
//...
class InstanceData
{
public:
InstanceData(TCHAR* strIn) : strMessage(strIn),
{
charArrayPtr.insert(charArrayPtr.begin(), strMessage.begin(), strMessage.end())
charArrayPtr.push_back(0);
}

TCHAR* getMessage()
{ return &charArrayPtr[0]; }

private:
String strMessage;
std::vector<TCHAR> charArrayPtr;
};

这与您的类所做的一样,但主要区别在于它不执行任何手动动态分配代码。该类还可以安全地复制,这与具有动态分配的代码不同(缺少用户定义的复制构造函数和赋值运算符)。

std::vector 类已经取代了几乎在所有情况下都必须执行的new[]/delete[]。原因是 vector 将其数据存储在连续的内存中,与调用 new[] 没有什么不同。

关于c++ - TCHAR 数组的深拷贝被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26862466/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com