简体   繁体   English

用std :: shared_ptr分配类成员

[英]Allocating class member with std::shared_ptr

Is my assumption, that in following example, memory referenced by b will be deallocated once instance of A goes out of scope at end of func() , correct? 我的假设是,在下面的示例中,一旦A实例超出func()的范围,对b引用的内存将进行重新分配,对吗?

class A{
public:
   A() {
        b = std::shared_ptr<char>(new char[100] { 0 } );
   }
   char* b;
}

void func {
   A a;
}

No, not correct. 不,不正确。 b is of type char * and you assign to it a shared_ptr<char> . b的类型为char *并为其分配了shared_ptr<char> You should get a compilation error. 您应该得到一个编译错误。

Furthermore, the constructor is private , another compilation error. 此外,构造函数是private ,这是另一个编译错误。

And how do you access b in func() ? 以及如何在func()访问b It is private in A . 它在A是私有A

Obviously your exercise is incomplete... so I just go from what you provided. 显然您的锻炼还不完整...所以我只是从您提供的内容出发。

Also I suggest to use unique_ptr in case you can say it is a unique ownership (which it appears to be in my opinion). 另外,我建议使用unique_ptr ,以防您可以说这是唯一所有权(在我看来这是唯一的)。

This compiles: 这样编译:

#include <memory>
#include <iostream>

class A {
public:

    A() {
        std::cout << "A created with unique pointer" << std::endl;
        b = std::unique_ptr<char>(new char[100] {
            0
        });
    }

    ~A() {
        std::cout << "A destroyed" << std::endl;
    }

private:
    std::unique_ptr<char> b;
};

void func() {
    A a;
}

int main() {
    std::cout << "Call func()" << std::endl;
    func();
    std::cout << "func() called" << std::endl;
    return 0;
}

And at the end of func() A is destroyed and with it the unique_ptr . 并且在func()的末尾销毁了A并且销毁了unique_ptr

However, ask yourself if you really need to use pointer? 但是,问问自己是否真的需要使用指针? In your case an automatic variable should be just fine; 在您的情况下,自动变量应该就可以了; it does the same (ie being destroyed when func() exits. 它执行相同的操作(即当func()退出时被销毁。

You're assigning to a char* member, so I'm pretty sure the shared_ptr is cleaned up as soon as the assignment completes (because it wasn't stored to another shared_ptr that would maintain the reference count). 您正在分配给char*成员,因此,我很确定在分配完成后就将对shared_ptr进行清理(因为它没有存储到其他保持引用计数的shared_ptr中)。

If you want to use shared_ptr s, you have to use them consistently; 如果要使用shared_ptr ,则必须始终使用它们。 a raw pointer class member can't manage anything for you. 原始指针类成员无法为您管理任何事情。 The pointer is still initialized to where the memory was allocated, but it's not allocated anymore; 指针仍然初始化为分配内存的位置,但是不再分配。 accessing it even a line later in the constructor would be undefined behavior/a use-after-free bug. 即使在构造函数中稍后访问它,也将是未定义的行为/释放后使用的错误。

In any event, not safe because default shared_ptr uses delete , not delete[] . 无论如何,这是不安全的, 因为默认的shared_ptr使用delete而不是delete[] Is there some reason a std::shared_ptr<std::array<char, 100>> couldn't be used? 是否有某种原因不能使用std::shared_ptr<std::array<char, 100>>

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

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