Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为共享类创建构造函数_C++_Typedef_Smart Pointers - Fatal编程技术网

C++ 为共享类创建构造函数

C++ 为共享类创建构造函数,c++,typedef,smart-pointers,C++,Typedef,Smart Pointers,我想隐藏我正在使用一个共享指针,并使它看起来像我只有一个普通类。原因是绝对不能复制我的对象,但我仍然希望用户能够创建带有{obj1,obj2}的向量。有没有一种方法可以像初始化构造函数一样初始化测试对象,或者我必须使用make_shared来初始化它?您可以使用类包装std::shared_ptr,如下所示 #include <iostream> #include <vector> class TestX { public: int i; TestX(i

我想隐藏我正在使用一个共享指针,并使它看起来像我只有一个普通类。原因是绝对不能复制我的对象,但我仍然希望用户能够创建带有{obj1,obj2}的向量。有没有一种方法可以像初始化构造函数一样初始化测试对象,或者我必须使用make_shared来初始化它?

您可以使用类包装std::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;
}

您还可以从共享的ptr派生

包括 包括 包括 类TestX{ 公众: int i; TestXint inp1:iinp1{} }; 结构测试:std::shared\u ptr{ 测试int x:std::shared_ptr{std::make_sharedx}{ }; int main { 试验a4;
std::我能喜欢吗?自动测试val{return std::make_sharedval;}然后自动a=Test4;但我不确定“hide”是什么意思。我相信添加“auto Testint val{return std::make_sharedval;}”`会与我的typedef冲突吗?这意味着任何接受Test作为参数的函数,都必须写出std::shared_ptr。然后调用函数TestMake?也有,但我不确定你在寻找什么…所以,我必须问,如果没有人可以使用它,为什么要使用共享指针?我没有感觉到op在寻找它但是我可能错了。@lakeweb我理解的是op想要使用shared_ptr并隐藏它,这是一个完美的方法,不是吗?谢谢,这看起来很有趣!你能解释一下TestXTestX const&=delete;做什么吗?@dockynodyerror删除复制构造函数或阻止从类复制实例。@lakeweb我不知道我不知道我为什么回答这个问题!我觉得这是个xy问题。
#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;
}