I would like to reuse the shared_ptr
among a few member functions in a class.
#include <iostream>
#include <memory>
class TestClass
{
private:
std::shared_ptr<int> int_shared_ptr;
public:
TestClass()
{
std::cout << "I will create a shared ptr object here.";
std::shared_ptr<int> int_ptr (new int(10));
std::shared_ptr<int> int_shared_ptr(int_ptr);
std::cout << "The created shared ptr has value of " << *int_shared_ptr << "\n";
}
void check_if_shared()
{
std::cout << "The created shared ptr has value of " << int_shared_ptr << "\n";
}
};
int main(){
auto tc = TestClass();
tc.check_if_shared();
}
Output
I will create a shared ptr object here.The created shared ptr has value of 10
The created shared ptr has value of 0
The int_shared_ptr
seems destroyed once it leaves the constructor. Can anyone suggest a way to keep the shared pointer after leaving the constructor?
The line
std::shared_ptr<int> int_shared_ptr(int_ptr);
creates a function local variable of the same name as the member variable. The member variable is left default-initialized. Use:
TestClass() : int_shared_ptr(new int(10))
{
std::cout << "The created shared ptr has value of " << *int_shared_ptr << "\n";
}
It is more idiomatic to use std::make_shared
:
TestClass() : int_shared_ptr(std::make_shared<int>(10))
{
std::cout << "The created shared ptr has value of " << *int_shared_ptr << "\n";
}