gpt4 book ai didi

c++ - 如何将 memcpy 与 unique_ptr 一起使用

转载 作者:行者123 更新时间:2023-12-03 07:07:11 32 4
gpt4 key购买 nike

当我遇到这个时,我正在尝试学习智能指针。

{ //Example 1
//String to be copied
std::string strHello = "HelloWorld1";
int size = strHello.length();

//Creating Ptr using make_unique
std::unique_ptr<char[]> pstrText;
pstrText = make_unique<char[]>(size + 1); // Allocating +1 for \0

//Copying values to the new pointer
int r = memcpy_s(pstrText.get(), size + 1, strHello.c_str(), size);

//Printing
std::cout << pstrText.get() << std::endl;
}

{ //Example 2
//String to be copied
std::string strHello = "HelloWorld2";
int size = strHello.length();

//Creating Ptr using make_unique
std::unique_ptr<char[]> pstrText;
pstrText = make_unique<char[]>(size);

//Copying values to the new pointer
int r = memcpy_s(pstrText.get(), size, strHello.c_str(), size);

//Printing
std::cout << pstrText.get() << std::endl;
}
{//Example 3

//String to be copied
std::string strHello = "HelloWorld3";
int size = strHello.length();

//Creating Ptr using make_unique
std::unique_ptr<char[]> pstrText;
pstrText = make_unique<char[]>(size + 1); //Allocating + 1

//Copying values to the new pointer
int r = memcpy_s(pstrText.get(), size, strHello.c_str(), size);

//Printing
std::cout << pstrText.get() << std::endl;
}

{//Example 4

//String to be copied
std::string strHello = "HelloWorld4";
int size = strHello.length();

//Creating Ptr using make_unique
std::unique_ptr<char[]> pstrText;
pstrText = make_unique<char[]>(size);

//Copying values to the new pointer
int r = memcpy_s(pstrText.get(), size + 1, strHello.c_str(), size);

//Printing
std::cout << pstrText.get() << std::endl;
}

使用 VS 2013 Debug(Win32) 的输出如下:

HelloWorld1
HelloWorld2²²²²½½½½½½½½■
HelloWorld3
HelloWorld4²²²²½½½½½½½½■
  1. 如果示例 1 是正确的,为什么示例 3 也给出了正确的输出?
  2. 末尾的垃圾值表示什么?
  3. 为什么编译器没有抛出任何错误或异常?
  4. 在示例4中,当我们尝试在最后复制一个值但未初始化时为什么没有错误
  5. 在这种情况下,我们如何正确初始化智能指针?如果它是 BYTE 数组而不是 char,会有什么改变吗?

最佳答案

你需要知道的两件事:

首先是在 C++ 中 memcpy_s是 Microsoft VC++ CRT 特定的扩展。它存在于 C 中(添加到 C11 标准中),但即便如此,Microsoft 对安全功能的实现也常常不遵循 C 标准。

第二件事,也是导致问题的原因,是最后一个参数是要复制的字节数。由于您只在此处指定了 size,因此您的调用不会复制字符串空终止符。您需要复制 size + 1 字节:

int r = memcpy_s(pstrText.get(), size + 1, strHello.c_str(), size + 1);
// ^^^^
// Copy plus one, to also copy the null-terminator

关于c++ - 如何将 memcpy 与 unique_ptr 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60053933/

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