【发布时间】:2020-12-04 07:25:04
【问题描述】:
我正在尝试创建一个指向返回为 const int& 的值的智能指针 (unique_ptr),但我的问题可以简单地总结为:
const int value = 5;
const int * ptr{nullptr};
ptr = &value;
这工作,并按预期编译。尝试使用智能指针进行相同操作时:
const int value = 5;
std::unique_ptr<const int> ptr{nullptr};
ptr = &value;
这样我得到编译错误:
no operator "=" matches these operands -- operand types are: std::unique_ptr<const int, std::default_delete<const int>> = const int *
是否可以获得与普通 C 指针相同的行为?
编辑: 我看到我原来的问题太简单了:这是更高级的版本:
int value = 5;
const int& getValue(){
return value;
};
std::unique_ptr<const int> ptr1{nullptr};
const int * ptr2{nullptr};
ptr1 = std::make_unique<const int>(getValue());
ptr2 = &getValue();
std::cout << "ptr1: " << *ptr1 << "\n";
std::cout << "ptr2: " << *ptr2 << "\n";
value++;
std::cout << "ptr1: " << *ptr1 << "\n";
std::cout << "ptr2: " << *ptr2 << "\n";
打印出来:
ptr1: 5
ptr2: 5
ptr1: 5
ptr2: 6
正如你看到的行为有点不同,现在我相信这是因为make_unique 复制了指向的内存地址中的值
【问题讨论】:
标签: c++ c++11 smart-pointers unique-ptr