make_unique可以存储文字或 iostream 输入吗?

can make_unique store the literals or iostream inputs?

本文关键字:iostream 输入 文字 存储 unique make      更新时间:2023-10-16

当我使用 char 类型的普通指针来存储来自<iostream>bycin>>ptr的输入时,它被转换为数组。

我推断这是因为cout<<ptr;给出了存储的字符串并且没有给出地址。地址由cout<<&pointer;.

但是当我改用make_unique时,它给出了错误。 为什么他们的行为相同。 请解释这一点,以及使用 make_unique 将字符串输入存储为字符数组的正确方法是什么。 我已经附加了使用的代码。

#include<iostream>
#include<string>
#include<memory>
using namespace std;
int main(){

//using of std::string
string str;
cout<<"Enter a str: ";
cin>>str;cout<<endl;
cout<<str<<"n";

// using of ordinary pointer
char* str2;//as if u r assigning array to a pointer
cout<<"Enter a str: ";
cin>> str2;cout<<endl;
cout<<str2;
cout<<endl;
//using of arrays
char c[] = "ghfgtgbbb";
cout<<c;
char* cPtr = c;
cout<<"n"<<cPtr;
cout<<endl;

//using of mak_unique (gives errors)
auto str3Ptr = make_unique<char>();
cout<<"Enter a str: ";
cin>> str3Ptr;cout<<endl;
cout<<str3Ptr;
cout<<endl;

return 0;}

首先,

// using of ordinary pointer
char* str2;//as if u r assigning array to a pointer
cout<<"Enter a str: ";
cin>> str2;cout<<endl;
cout<<str2;
cout<<endl;

可能"有效",但它实际上是未定义的行为。char* str2;创建一个指向某物的指针,但我们不知道是什么。 尝试使用cin>> str2将数据存储在其中是未定义的行为,因为您无权写入任何str2指向的内容。 所以应该避免这个代码块。

现在让我们看看

//using of arrays
char c[] = "ghfgtgbbb";
cout<<c;
char* cPtr = c;
cout<<"n"<<cPtr;
cout<<endl;

这更好,c是一个 10 个字符的数组,并且cPtr初始化为指向它,因此它是一个有效的指针。 你不用它输入,但你可以,但你必须确保不超过 9 个字符(你必须为空终端留出空间(。

现在我们将查看unique_ptr代码。 在

//using of mak_unique (gives errors)
auto str3Ptr = make_unique<char>();
cout<<"Enter a str: ";
cin>> str3Ptr;cout<<endl;
cout<<str3Ptr;
cout<<endl;

你基本上做了与第一个代码块相同的事情。auto str3Ptr = make_unique<char>();创建指向单个char的唯一指针。 所以至少你已经初始化了变量,但它不会大到足以存储输入。 您需要使用数组版本并为所需的输入分配足够的空间。 那看起来像

auto str3Ptr = make_unique<char[]>(80);
^^ number of elements to allocate

您也不能将其与cincout一起使用,因为它不提供重载来执行此操作。 您要么必须编写自己的代码,要么如果指针类型存在重载,则可以使用get来获取指向存储在unique_ptr中的内容的实际指针。

所以,这给我们留下了

//using of std::string
string str;
cout<<"Enter a str: ";
cin>>str;cout<<endl;
cout<<str<<"n";

这是在C++中处理字符串的正确方法。 它将处理分配和解除分配,并构建为与标准流一起使用。