为了防止发生这种情况,您可以选择采用一个指针(因为Weep(&std::vector<int>{1,2,3})不允许这样做),也可以采用非常量引用,这也会在临时情况下出错。
Woop(const std::vector<int> *nums);
Woop(std::vector<int> *nums);
Woop(std::vector<int>& nums);
这些仍然不能保证该值仍然有效,但是至少可以停止最简单的错误,不创建副本,也不需要nums以特殊方式创建(例如,std::shared_ptr或std::weak_ptr确实)。
std::scoped_lock引用互斥量将是一个示例,而实际上并不需要唯一/共享/弱ptr。通常,它们std::mutex只会是基本成员或局部变量。您仍然必须非常小心,但是在这些情况下,通常很容易确定使用寿命。
std::weak_ptr是非拥有的另一种选择,但是您随后迫使调用者使用shared_ptr(因此也分配了堆分配),有时这是不需要的。
如果可以,则可以避免该问题。
如果Woop应该拥有所有权,则要么将其作为r值传递并移动(并完全避免指针/引用问题),要么unique_ptr如果不能移动值本身或希望指针保持有效,请使用。
// the caller can't continue to use nums, they could however get `numbers` from Woop or such like
// or just let Woop only manipulate numbers directly.
Woop(std::vector<int> &&nums)
: numbers(std::move(nums)) {}
std::vector<int> numbers;
// while the caller looses the unique_ptr, they might still use a raw pointer, but be careful.
// Or again access numbers only via Woop as with the move construct above.
Woop(std::unique_ptr<std::vector<int>> &&nums)
: numbers(std::move(nums)) {}
std::unique_ptr<std::vector<int>> numbers;
或者,如果所有权是共享的,则可以使用shared_ptr所有内容,并且它将与最终引用一起删除,但是如果过度使用,这会使跟踪对象生命周期变得非常混乱。
std::unique_ptr对于专有所有权std::shared_ptr或共享所有权,或std::weak_ptr至少识别丢失的数据)。