<分区>
我在这些项目中看到了这些指针类混合在一起的情况。
有时他们使用 std:unique_ptr、shared_ptr,有时我看到 Microsoft::WRL::ComPtr。
只是想知道有什么区别,我怎么知道该使用哪个?
<分区>
我在这些项目中看到了这些指针类混合在一起的情况。
有时他们使用 std:unique_ptr、shared_ptr,有时我看到 Microsoft::WRL::ComPtr。
只是想知道有什么区别,我怎么知道该使用哪个?
最佳答案
std::unique_ptr
表示指向对象的唯一 指针,因此您无法复制该指针;但您仍然可以移动指针。
例如
auto ptr = std::make_unique<float>(5.0f);
std::unique_ptr other_ptr = ptr;
不会编译,但是
auto ptr = std::make_unique<float>(5.0f);
std::unique_ptr other_ptr = std::move(ptr);
会。
std::shared_ptr
表示指向多个其他 shared_ptr
可能指向的对象的指针。可复制、可移动。
你不会一直使用 shared_ptr
而不是 unique_ptr
的原因是 shared_ptr
在构建和解构时会变慢,而且任何时候你需要将它传递给一个函数,你可能会招致这种缓慢的(反)构造。
举个例子
auto ptr = std::make_shared<float>(5.0f);
std::shared_ptr other_ptr = ptr;
(可能很多)比将原始指针移动到新指针要慢,因为编译器必须跟踪有多少 shared_ptr
实例指向该对象,以便当 shared_ptr
被解构,如果它是指向该对象的最后一个指针,它将被删除。
至于ComPtr
...除非绝对必要,否则请不要使用它。这几乎从不。您可能看到它在您引用的项目中使用的原因是某些 Microsoft 特定 API 使用它,这是您必须使用它的时候之一。
为了展示这些不同智能指针的优点和/或缺点,以及何时应该选择它们,确实需要一个像样的示例程序。所以,给你!
void f(std::unique_ptr<float> p){}
void f(std::shared_ptr<float> p){}
void g(std::unique_ptr<float> &p){}
void g(std::shared_ptr<float> &p){}
int main(int argc, char *argv[]){
auto uptr = std::make_unique<float>(6.9f);
auto sptr = std::make_shared<float>(4.20f);
// f(uptr);
// error, trying to make a copy of a unique_ptr
f(sptr);
// fine, shared_ptr may be copied
f(std::make_unique<float>(6.9f));
f(std::make_shared<float>(4.20f));
// both fine, value initialized in function call and moved into function.
g(uptr);
g(sptr);
// both fine, shared and unique pointers may be passed by reference
// as no copy or move is made.
}
关于C++微软的ComPtr和c++的unique_ptr、shared_ptr有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770933/