gpt4 book ai didi

c++ - 非拥有指针作为现代 C++ 中的类成员

转载 作者:行者123 更新时间:2023-12-01 14:48:46 25 4
gpt4 key购买 nike

我一直在研究智能指针以及何时应该使用它们与原始指针。我认为拥有指针的对象应该将该指针实例化为智能指针(unique_ptr/shared_ptr)。

然后,当将该指针传递给不需要其所有权的各种函数/类时,传递一个原始指针(通过 .get() 从智能指针获得),并注意将原始指针发送到的函数/类将永远不要超过拥有它的函数/类的范围。

这种理解是否正确?这对我来说似乎很有意义,但是当我开始实现特定的例程时,我的信心下降了。

以下代码将更好地解释我当前挂断的位置。我有一个成员 vector unique_ptr转至 Mesh Scene 中的对象.然后我传递创建的原始指针 unique_ptr实例化 Actor对象,最后移动 unique_ptrscene->meshes vector 。

事实是Actor有一个 Mesh*作为成员(member),只要在任何一个范围内都不会被认为是不好的做法Actor永远不会比拥有者的生命周期长 scene->meshes元素?

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

class Mesh
{
public:
int vec = 1;
int ind = 2;
};

class Actor
{
private:
Mesh * mesh;
public:
Actor(Mesh* m) {
this->mesh = m;
}
};

class Scene
{
public:
// meshes will always outlive all instantiated actors
std::vector<std::unique_ptr<Mesh>> meshes;
std::vector<Actor> actors;
};


int main()
{
auto scene = std::make_unique<Scene>();

auto m1 = std::make_unique<Mesh>();
auto a1 = Actor(m1.get());
scene->meshes.push_back(std::move(m1));

auto m2 = std::make_unique<Mesh>();
auto a2 = Actor(m2.get());
scene->meshes.push_back(std::move(m2));

std::cout << scene->meshes.size();

std::cin.get();
return 0;
}

最佳答案

Is the fact that an Actor has a Mesh* as a member not considered bad practice as long as ...



当然,这是一种代码气味。该类很容易被滥用。必须仔细记录构造函数存储角色生命周期的指针,以提醒用户维护指向网格的生命周期。

在这种情况下,共享所有权会更安全。但如果性能开销很大,它并不总是最佳选择。

关于c++ - 非拥有指针作为现代 C++ 中的类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60174402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com