Create a constructor for a shared_ptr

#include <iostream>
#include <vector>

class TestX {
public:
    int i;
    TestX(int inp1) : i(inp1){}

};
using Test = std::shared_ptr<TestX>;

int main()
{
    Test a(4);
    std::cout << a->i << std::endl;
}

I wanted to hide away that I am using a shared pointer, and make it look like I have just a regular class. The reason is that it is essential that my objects are never copied, but I still want the users to be able to create a vector with {obj1, obj2}. Is there a way to initialize a Test object as if there was a constructor, or do I have to use make_shared to initialize it?

Answer

You can use a class to wrap a std::shared_ptr, as follows

#include <iostream>
#include <vector>
#include <memory>

struct TestX {
    int i;
    TestX(int inp1) : i(inp1){}
    TestX(TestX const &) = delete;

};

struct Test {
    std::shared_ptr<TestX>test;
    Test(int inp1) : test{std::make_shared<TestX>(inp1)}{}
    int& get_i (){
        return test -> i;
    }

};

int main()
{
    Test a(4);
    Test b(1);
    auto v = std::vector{a, b};
    std::cout << a.get_i() << std::endl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *