我尝试学习如何使用智能指针。我使用了很长一段时间的普通指针,我认为我需要提升我的技能。
我做了一些研究,我了解智能指针的某些方面,但我尝试在一个清晰的项目中实现以了解智能指针是如何工作的。我试试:
#include <iostream>
#include <array>
#include <memory>
class Entity
{
public:
Entity()
{
std::cout << "Entity called!" << std::endl;
}
~Entity()
{
std::cout << "Entity destroyed!" << std::endl;
}
void print() { std::cout << "Message!"; }
};
int main()
{
std::shared_ptr<int>f1(new int[100]);
f1.get()[1] = 1;
std::cout << f1.get()[1];
}
一切都好,消息已打印。但是当我尝试时:
#include <iostream>
#include <array>
#include <memory>
class Entity
{
public:
Entity()
{
std::cout << "Entity called!" << std::endl;
}
~Entity()
{
std::cout << "Entity destroyed!" << std::endl;
}
void print() { std::cout << "Message!"; };
};
int main()
{
std::shared_ptr<Entity>f1(new Entity[100]);
f1.get()[1].print();
}
我收到此错误: [图片] https://i.imgur.com/U30gTgC.png[/img]
下一个:
int main()
{
std::shared_ptr<Entity>f1(new Entity[100]);
(f1.get() + 1)->print();
}
同样的错误。
我尝试使用 std::make_shared:
#include <iostream>
#include <array>
#include <memory>
class Entity
{
public:
Entity()
{
std::cout << "Entity called!" << std::endl;
}
~Entity()
{
std::cout << "Entity destroyed!" << std::endl;
}
void print() { std::cout << "Message!"; };
};
int main()
{
std::shared_ptr<Entity>f1 = std::make_shared<Entity>();
f1->print();
}
一切正常。
我尝试用 int 分配 continue 内存:
#include <iostream>
#include <array>
#include <memory>
class Entity
{
public:
Entity()
{
std::cout << "Entity called!" << std::endl;
}
~Entity()
{
std::cout << "Entity destroyed!" << std::endl;
}
void print() { std::cout << "Message!"; };
};
int main()
{
std::shared_ptr<int>f1 = std::make_shared<int>(100);
f1.get()[1] = 10;
std::cout << f1.get()[1];
}
消息已打印,输出:10 但错误: https://i.imgur.com/UPu7VZo.png
我尝试了另一种方式:
int main()
{
std::shared_ptr<int>f1 = std::make_shared<int>(100);
*(f1.get() +1) = 10;
std::cout << *(f1.get() + 1);
}
同样的错误。
std::shared_ptr<Entity[]>f1 = std::make_shared<Entity[]>(new Entity[100]);
我有错误...
我尝试做这样的事情:
int main()
{
Entity* f1 = new Entity[100];
f1[0].print();
f1[1].print();
f1[2].print();
}
但我想使用智能指针。
对于 int,我想像这样分配一些值:
int main()
{
int* f1 = new int[100];
f1[0] = 14;
f1[1] = 20;
f1[2] = 5;
}
我怎样才能用智能指针做这样的事情。我想使用:std::make_shared(new Entity[100]) 或类似的东西。
我可以尝试使用 vector 或数组之类的库,但我暂时不想使用这个库。我想暂时保持我的代码清晰。在我理解 100% 智能指针后,我将使用数组和 vector 库
最佳答案
没有
std::shared_ptr<Entity[]> f1 = std::make_shared<Entity[]>(new Entity[100]);
但是
std::shared_ptr<Entity[]> f1 = std::make_shared<Entity[]>(100);
甚至更简单
auto f1 = std::make_shared<Entity[]>(100);
当你使用 make_shared
时,你不应该使用 new
。 make_shared
的要点之一是比使用 new
时更有效地分配内存。
注意:make_shared
的数组形式需要C++20。
关于c++ - 智能指针(shared_ptr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929924/