Search code examples
c++c++11shared-ptrsmart-pointers

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?

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

void func {
   A a;
}

Solution

  • 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.