#include <iostream>
#include <memory> // unique_ptr
using namespace std;
int main()
{
std::unique_ptr<char*> char_ptr;
char_ptr = (char*)"anisha";
return 0;
}
我想为代码中其他地方的unique_ptr分配一些值。
这将产生以下错误:char_ptr = (char*)"anisha";
error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<char*>’ and ‘char*’)
char_ptr = (char*)"anisha";
如何在声明unique_ptr
后为其赋值?
答案 0 :(得分:2)
您不能天真地将指向字符串文字的指针存储在unique_ptr
中。这里的指针假定它拥有被引用的对象并可以释放它。但是它不能归指针所有,因为字符串文字具有静态的存储持续时间。
如果要将可修改的C字符串存储在unique_ptr
中,则需要进行变音和复制,则不能用演员表打翻字型系统并过着幸福的生活。 / p>
因此将字符串文字转换为唯一指针的实用程序如下所示:
template<std::size_t N>
auto literal_dup(char const (&lit)[N]) {
auto ptr = std::make_unique<char[]>(N);
std::copy(lit, lit + N, &ptr[0]);
return ptr;
}
使用它将如下所示:
std::unique_ptr<char[]> c_string;
c_string = literal_dup("anisha");
我们需要使用unique_ptr
的数组形式来确保它正确地释放了缓冲区,并且没有未定义的行为。
答案 1 :(得分:1)
使用std :: make_unique。 这是您的代码编辑-
#include <iostream>
#include <memory> // unique_ptr
using namespace std;
int main()
{
std::unique_ptr<char*> char_ptr;
//char_ptr = (char*)"anisha";
char_ptr = std::make_unique<char*>((char*)"anisha");
return 0;
}