简体   繁体   English

我可以将智能指针用作 C++ 中的 class 成员吗?

[英]Can I use smart pointers as class members in C++?

I learned that unique pointers "die" at the end of a scope.我了解到唯一指针在 scope 的末尾“死亡”。 So how does it work in class members?那么它在 class 成员中是如何工作的呢? Does shared pointers work?共享指针有效吗?

Yes absolutely.是的,一点没错。 You can use them in classes as members.您可以在类中使用它们作为成员。

When its used as a member variable, the lifetime of the unique pointer is the lifetime of the object itself (unless you explicitly release them).当它用作成员变量时,唯一指针的生命周期是 object 本身的生命周期(除非您明确释放它们)。 When the object is destructed, the unique pointer and all the smart pointers will deallocate its memory.当 object 被破坏时,唯一指针和所有智能指针将释放其 memory。

Can I use smart pointers as class members in C++?我可以将智能指针用作 C++ 中的 class 成员吗?

Yes.是的。 Pretty much any class can be a member except for classes that cannot be instantiated at all.除了根本无法实例化的类之外,几乎任何 class 都可以成为成员。

I learned that unique pointers "die" at the end of a scope.我了解到唯一指针在 scope 的末尾“死亡”。

All automatic variables "die" at the end of scope. scope 末尾的所有自动变量“死”。 This property is not particular to smart pointers.此属性并非特定于智能指针。 Example:例子:

{
    int i = 42;
} // i "dies" here

A thing that makes smart pointers different from bare pointers is not that they "die" at the end of scope (because bare pointers also "die"), but rather what the smart pointers do when they "die".使智能指针与裸指针不同的一点不是它们在 scope 末尾“死亡”(因为裸指针也“死亡”),而是智能指针在“死亡”时做了什么。

A non-static member varible "dies" when the super object "dies".当超级 object “死”时,非静态成员变量“死”。

Does shared pointers work?共享指针有效吗?

Yes.是的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM