【发布时间】:2021-06-23 19:19:38
【问题描述】:
使用原始指针我可以做到:
int x = 10;
int* y = &x;
x = 20;
std::cout << *y; //prints 20
但是,我正在努力模仿 std::unique_ptr 的相同行为。我试过了:
int x = 10;
std::unique_ptr<int> y = std::make_unique(&x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int>(&x); //doesnt compile
std::unique_ptr<int&> y = std::make_unique(x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int&>(&x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int>(x); //compiles but prints y = 10, which is not the desired behaviour
我确信有办法,所以任何帮助表示赞赏。谢谢。
【问题讨论】:
-
@RemyLebeau 这是有道理的,所有关于不使用原始指针的讨论都让我明白了。耸耸肩。谢谢:)
-
一般来说使用原始指针并没有错,只要它们不用于处理所有权语义。不再推荐直接使用
new/delete,代替提供更强所有权语义的标准容器和智能指针。两种不同的东西。 -
请注意,如果您在 C++ 中通过反复试验进行编程,您将度过一段糟糕的时光。未定义行为潜伏在黑暗中,等待突袭毫无戒心的程序员。文档是你的朋友。
-
@alterigel 我正在阅读 cpp 参考,但它让我发疯了,因为它没有显示如何从参考中初始化唯一的 ptr! doh ...您不能这样做,因此它不在cpp参考中。应该已经阅读了小文本。
标签: c++ c++11 smart-pointers