gpt4 book ai didi

c++ - 有人能给我提供一个设置和检索 unique_ptr 的简单示例吗

转载 作者:行者123 更新时间:2023-11-28 02:27:41 28 4
gpt4 key购买 nike

我将如何使用智能指针编写以下内容:

class App
{
public:
Project* GetProject();
SetProject( Project* project );
private:
Project* project;
}

Project* project = new Project();
App* app = new App();

app.SetProject( project );
Project* retrievedProject = app.GetProject();

我最感兴趣的是方法参数和返回技术...这样正确吗?

class App
{
public:
void App::SetProject( unique_ptr<Project> project )
{
this->project.swap( project );
}

Project* App::GetProject() const
{
return this->project.get();
}
private:
unique_ptr< Project > project;
}

...

unique_ptr< Project > project( new Project() );
unique_ptr< App > app( new App() );

app.SetProject( project );
unique_ptr< Project > retrievedProject = app.GetProject();

这与这个问题有关:Should i stop using * pointers? - A few entry questions

我对现在的规则有点困惑...提前致谢!

编辑小问题:

Galik,您曾提到您很少想在函数调用之外声明 Project,然后将其传递给发布...我有以下内容(例如):

unique_ptr<Project>project( new Project() );
project.Title = "Bob";
project.Type = PROJECTYPE.DISTRIBUTION;
project.Manager = manager;

app.SetProject( project.release() );

这完全正常吗?我的问题是,我实际上是在为游戏创建工具,我担心随着垃圾收集的启动,不断标记删除会导致微卡顿……我只是担心而已吗?

最佳答案

这个问题的答案实际上取决于您想要做什么。您应该使用智能指针来表达所有权,并且您不应该真正传递关于您是否可以帮助它的智能指针。

如果例如您的App 类应该处理各种Project 对象并且只提供访问Project 发送给外部人员,那么您应该通过返回对该项目的 reference 来表达这一点。

通过这种方式,多个调用者可以访问 App 拥有的内部 Project

就像这样:

class Project
{
public:
void do_stuff() {}
};

// This class is the Project Owner
// Meaning it is responsible for
// managing its life-time
class App
{
public:
// return a reference expressing the caller
// does not gain ownership merely access
Project& GetProject() { return *project; }

// replace configured Project
// accepting a std::unique_ptr expresses the fact that
// this function takes ownership of the Project
void SetProject(std::unique_ptr<Project> project) { this->project = std::move(project); }

private:
std::unique_ptr<Project> project;
};

int main()
{
App app; // don't make pointers if we don't have to

// project has ownership of the raw pointer
std::unique_ptr<Project> project(new Project());

// std::move() transfers ownership to the function's parameter
app.SetProject(std::move(project));

// get a reference to the internal Project
Project& retrievedProject = app.GetProject();

// work with configured Project
retrievedProject.do_stuff();
}

关于c++ - 有人能给我提供一个设置和检索 unique_ptr 的简单示例吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980284/

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