【问题标题】:Create a constructor for a shared_ptr<MyClass>为 shared_ptr<MyClass> 创建一个构造函数
【发布时间】:2021-03-07 00:56:32
【问题描述】:
#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;
}

我想隐藏我正在使用共享指针,并让它看起来像我只有一个普通类。原因是我的对象永远不会被复制是很重要的,但我仍然希望用户能够使用{obj1, obj2} 创建一个向量。有没有办法像有构造函数一样初始化 Test 对象,还是我必须使用make_shared 来初始化它?

【问题讨论】:

  • 喜欢? auto Test(int val) { return std::make_shared&lt;TestX&gt;(val); } 然后auto a = Test(4); 但我不确定你所说的“隐藏”是什么意思。
  • 我相信添加 ` auto Test(int val) { return std::make_shared(val); }` 会和我的 typedef 冲突吗?这意味着任何接受 Test 作为参数的函数都必须写出std::shared_ptr&lt;TestX&gt;
  • 然后调用函数TestMake?
  • 还有std::enable_shared_from_this 但是我不确定你在找什么...
  • 那么,我要问了,如果没有人可以使用共享指针,为什么还要使用它?

标签: c++ typedef smart-pointers


【解决方案1】:

可以使用一个类来包装一个std::shared_ptr,如下

#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;
}

【讨论】:

  • 我没有感觉到操作员正在寻找什么。但我可能是错的。
  • @lakeweb 我的理解是操作想要使用shared_ptr 并隐藏它,这是一个完美的方法,不是吗?
  • 谢谢,这看起来很有趣!你能解释一下TestX(TestX const &amp;) = delete; 的作用吗?
  • @dockynodyerror 删除复制构造函数或阻止从类中复制实例。
  • @lakeweb 我不知道我为什么回答这个问题!我觉得这是xy 的问题。
【解决方案2】:

你也可以从 shared_ptr

派生
#include <iostream>
#include <vector>
#include <memory>

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

struct Test : std::shared_ptr<TestX>{
   Test( int x) : std::shared_ptr<TestX>{std::make_shared<TestX>(x)}{}
};

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

    Test b(1);
    auto v = std::vector{a, b};
}

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    相关资源
    最近更新 更多