使用智能指针指向const int的指针

时间:2020-08-14 11:50:05

标签: c++ c++11 smart-pointers unique-ptr

我正在尝试创建一个智能指针(unique_ptr),该智能指针指向返回为const int&的值,但是我的问题可以很容易地总结为:

 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在指向的内存地址中复制了值

2 个答案:

答案 0 :(得分:4)

docker build -t hello-cron . docker run -t -i hello-cron 不能直接由原始指针分配;您可以使用reset。但是,您不应该分配std::unique_ptr的地址(该地址在自动脱离作用域时会被破坏),value会尝试std::unique_ptr指针,并导致UB。< / p>

您可能想要

delete

编辑

出于使用smart pointers的目的,

使用智能指针可确保删除不再使用(引用)的对象。

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

答案 1 :(得分:1)

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

此行:

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

等效于:

auto ptr = new const int{5};

所以在你的行

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

ptr1指向类型为const int的新对象,并使用getValue()返回的值进行初始化。

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

*ptr.get() += 1;

您会得到编译错误,因为int是常量。