使用std :: shared_ptr分配类成员 [英] Allocating class member with std::shared_ptr

查看:154
本文介绍了使用std :: shared_ptr分配类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是我的假设,在下面的例子中, b 引用的内存将在 A 超出 func()结束的范围,是否正确?

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

void func {
A a;
}


解决方案

b 的类型为 char * ,并指定 shared_ptr< char> code>。



此外,构造函数是 private ,另一个编译错误。

如何访问 func()中的 b ?在 A 中是私人的。



显然你的锻炼不完全...所以我只是从你提供的。



此外,我建议使用 unique_ptr ,以防你可以说它是一个唯一的所有权



这会编译:

  #include < memory> 
#include< iostream>

class A {
public:

A(){
std :: cout< A unique 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;
}



销毁,并使用 unique_ptr



但是,问自己,你真的需要使用指针吗?在你的情况下,自动变量应该很好;它执行相同的操作(即在 func()退出时被销毁。


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?

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>. You should get a compilation error.

Furthermore, the constructor is private, another compilation error.

And how do you access b in func()? It is private in 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).

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.

However, ask yourself if you really need to use pointer? In your case an automatic variable should be just fine; it does the same (i.e. being destroyed when func() exits.

这篇关于使用std :: shared_ptr分配类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆