C++ 将现有值分配给 smart-ptrs?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20195611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning existing values to smart-ptrs?
提问by bluepanda
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.
我只是在学习智能指针,我在将变量的预先存在的位置分配给标准库的共享指针时遇到了麻烦。
For example, lets say you have an int x, which you do not know the value of. With normal pointers, I just did
例如,假设您有一个 int x,您不知道它的值。用普通的指针,我只是做了
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.
所以我对如何做到这一点感到相当迷茫。
回答by Mike Seymour
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.
您(通常)不会将智能指针指向现有变量。智能指针管理动态分配对象的生命周期,使用后将其删除;如果它试图删除它,将它指向未动态分配的内容将导致错误。
You would usually use new
or make_shared
to create an object, and create or assign a smart pointer with the result of that:
您通常会使用new
或make_shared
来创建一个对象,并使用其结果创建或分配一个智能指针:
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
is usually preferable to new
, since it makes better use of memory and gives stronger exception-safety.
make_shared
通常比 更可取new
,因为它可以更好地利用内存并提供更强的异常安全性。
回答by JBL
Shared pointers are used to manage dynamically allocated memory and more precisely, they manage the ownershipfor this memory.
共享指针用于管理动态分配的内存,更准确地说,它们管理此内存的所有权。
Basically, a smart pointer is a materialization of the Ressource Acquisition Is Initialization, or RAII. I strongly suggest you take a look at this principle, as it is extremely useful for managing resource ownership (basically, each time you need to acquire a resource, and release it, be it memory, a database connection, a file handler, a mutex, etc.).
基本上,智能指针是Ressource Acquisition Is Initialization或 RAII 的具体化。我强烈建议你看看这个原则,因为它对于管理资源所有权非常有用(基本上,每次你需要获取资源并释放它,无论是内存、数据库连接、文件处理程序、互斥锁, 等等。)。
What it does is basically guarantee that while someone points at the dynamically allocated memory it manages, then this memory will be available, and as soon as the last (smart) pointer to this memory goes out of scope, then delete
is called.
它所做的基本上是保证当有人指向它管理的动态分配的内存时,该内存将可用,并且一旦指向该内存的最后一个(智能)指针超出范围,就会delete
被调用。
Then, it makes no sense to use smart pointers with variable that have automatic storage duration (i.e. that are removed when they go out of scope or when the object they're member of goes itself out of scope or is deleted (if it was new'd).
然后,将智能指针与具有自动存储持续时间的变量一起使用是没有意义的(即,当它们超出范围时或当它们所属的对象超出范围或被删除时(如果它是新的) 'd)。
回答by comonad
as soon as the reference counter of the shared_ptr reaches zero, the object will be deleted by the last shared_ptr. with smart pointers you can specify the function which shall delete that object.
一旦 shared_ptr 的引用计数器达到零,该对象将被最后一个 shared_ptr 删除。使用智能指针,您可以指定删除该对象的函数。
the Deleter is a simple function (defaults to the usual operator delete) that has to be bound to the smart pointer, either statically via template parameter (see unique_ptr) or dynamically via constructor parameter (see shared_ptr).
Deleter 是一个简单的函数(默认为通常的操作符 delete),它必须绑定到智能指针,通过模板参数静态地(参见unique_ptr)或通过构造函数参数动态地(参见shared_ptr)。
// dynamically via shared_ptr:
// shared_ptrs share the pointer to the Deleter
// because they already share a common data structure for reference counting.
auto ignore = [](int* o){
std::cout<<"i will refuse to delete this object: " << o << "\n";
std::cout<<"not my responsibility." <<std::endl;
};
std::shared_ptr<int> sptr(&x,ignore);
//statically via unique_ptr:
// actually, the unique_ptr is as data structure not more than a regular pointer.
// but a pointer with special copy-constructor and destructor,
// which will most likely be inlined.
// there is no space to store a reference to a Deleter dynamically.
struct IgnorantDeleter{
void operator()(int* o){
std::cout<<"who ate my cake? " << o << "\n";
std::cout<<"but i baked it." <<std::endl;
}
};
std::unique_ptr<int,IgnorantDeleter> uptr(&x);
回答by Ivaylo Strandjev
You should not create a smart pointer pointing to an object that is not dynamically allocated. Otherwise the smart pointer may try to delete the allocated memory which in turn will cause an error.
您不应创建指向未动态分配的对象的智能指针。否则智能指针可能会尝试删除分配的内存,这反过来会导致错误。