使用 getline 通过传入智能指针参数来读取文本

Using getline to read text by passing in smart pointer argument

智能指针通常可以用在所有使用原始指针的地方(或者有人告诉我)。假设我分配了一个包含 256 个字符的数组并使用 std::cin.getline()

读入一行文本
char* text { new char[256] };
auto smart_text { std::make_unique<char[]>(256) };

std::cin.getline(text, 256); // legal
std::cin.getline(smart_text, 256); // illegal

我的问题本质上是为什么我不能像使用 text 一样使用 smart_text。两者都是指向字符数组的指针,只是它们的管理方式不同。

我的猜测是智能指针是 STL 的抽象,std::getline 是仅接受原始指针参数的遗留代码。在这种情况下,以下是解决问题的 "right way" 吗?

std::cin.getline(smart_text.get(), 256);

在这种情况下,我们只是在抽象下传递指针的内存地址?

My question is esentially why I can't use smart_text the same way I use text.

因为智能指针没有隐式到原始指针的转换。要在使用原始指针的地方传递智能指针,您需要 显式 转换以访问智能指针持有的原始指针。

My guess is that the smart pointer is an abstraction from the STL and std::getline is legacy code that only accepts a raw pointer argument.

1.

1. STL 现在被称为 "standard library",你的意思是 std::istream::getline() 而不是 std::getline(),两者都不是遗留的。

In this case, would the following be the "right way" to approach the problem?

std::cin.getline(smart_text.get(), 256);

是的。

In which case we're simply passing in the memory address of the pointer underneath the abstraction?

是的。