将现有值分配给smart-ptrs? [英] Assigning existing values to smart-ptrs?
问题描述
我只是在学习智能指针,而在将变量的现有位置分配给标准库的共享指针时遇到了麻烦.
I am just learning about smart pointers, and I am having trouble assigning a pre-existing location of a variable to the standard library's shared pointer.
例如,假设您有一个不知道其值的int x.使用普通的指针,我就做到了
For example, lets say you have an int x, which you do not know the value of. With normal pointers, I just did
int* ptr;
ptr = &x;
我尝试了使用共享指针的尝试,
I tried both that with shared pointers, and
std::tr1::shared_ptr<int> ptr;
ptr = std::make_shared<int> (&x)
所以我对如何做到这一点很迷茫.
So i'm fairly lost as to how to do it.
推荐答案
您通常不会(但通常)将智能指针指向现有变量.智能指针管理动态分配对象的生命周期,使用后将其删除;如果将其指向未动态分配的内容,则尝试删除它会导致错误.
You wouldn't (usually) make a smart pointer point to an existing variable. A smart pointer manages the lifetime of a dynamically allocated object, deleting it after use; pointing it to something that wasn't dynamically allocated will cause an error if it tries to delete it.
通常将使用new
或make_shared
创建对象,并使用以下结果创建或分配智能指针:
You would usually use new
or make_shared
to create an object, and create or assign a smart pointer with the result of that:
std::shared_ptr<int> ptr(new int(42)); // Create a new pointer to manage an object
ptr.reset(new int(66)); // Reset to manage a different object
ptr = std::make_shared<int>(53); // Use `make_shared` rather than `new`
make_shared
通常比new
更可取,因为它可以更好地利用内存并提供更强的异常安全性.
make_shared
is usually preferable to new
, since it makes better use of memory and gives stronger exception-safety.
这篇关于将现有值分配给smart-ptrs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!