为 shared_ptr<MyClass> 创建构造函数
Create a constructor for a shared_ptr<MyClass>
#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;
}
我想隐藏我正在使用共享指针,并让它看起来像我有一个普通的 class。原因是我的对象永远不会被复制是很重要的,但我仍然希望用户能够使用 {obj1, obj2}
创建一个向量。有没有办法像有构造函数一样初始化 Test 对象,还是我必须使用 make_shared
来初始化它?
可以用一个class包裹一个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;
}
您还可以从 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};
}
#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;
}
我想隐藏我正在使用共享指针,并让它看起来像我有一个普通的 class。原因是我的对象永远不会被复制是很重要的,但我仍然希望用户能够使用 {obj1, obj2}
创建一个向量。有没有办法像有构造函数一样初始化 Test 对象,还是我必须使用 make_shared
来初始化它?
可以用一个class包裹一个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;
}
您还可以从 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};
}