繁体   English   中英

使用智能指针指向 const int

[英]pointer to const int using smart pointer

我正在尝试为返回为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复制了指向的 memory 地址中的值

std::unique_ptr不能直接由原始指针赋值; 你可以使用reset 但是您不应该分配value的地址(当自动离开 scope 时会被破坏), std::unique_ptr将尝试delete指针并导致 UB。

你可能想要

int value = 5; // we'll constructor a new object, value doens't need to be const
std::unique_ptr<const int> ptr{nullptr};
ptr = std::make_unique<const int>(value); // construct a new object and pass the ownership to ptr

编辑

为了使用智能指针

智能指针用于确保 object 在不再使用(引用)时被删除。

如果您不希望智能指针管理 object,或者不能让智能指针拥有 object,则不应使用智能指针。 对于这种特殊情况,我认为使用原始指针就可以了。

std::unique_ptr是原始指针和 memory 分配机制的包装器。 更多的是关于 memory 的分配。 它旨在自动创建和销毁对象。

这一行:

auto ptr = std::make_unique<const int>(5);

相当于:

auto ptr = new const int{5};

所以在你的行中

ptr1 = std::make_unique<const int>(getValue());

ptr1 指向一个新的 const int 类型的 object,用 getValue() 返回的值初始化。

而且您不会在程序中更改此值。 如果您尝试这样:

*ptr.get() += 1;

你会得到编译错误,因为 int 是 const。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM