将shared

编程入门 行业动态 更新时间:2024-10-23 23:21:25
本文介绍了将shared_ptr设置为指向现有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于下面的代码,我想知道如何设置 std :: shared_ptr 指向给定的对象在两个成员函数。在主函数中分配的 Vector3 对象在程序结束之前不会被删除。

#include< memory> #include< vector> 使用std :: vector; using std :: shared_ptr; class Vector3 { // ... }; class Face { vector< shared_ptr< vector3> > vtx; public: void addVtx(const Vector3& vt) { // vtx.push_back < - 如何push_back? } void setVtx(const int v,const Vector3& vt) { if(vtx.size()> 0&& v& ; vtx.size()) { // vtx [v] =& vt; < - 如何分配? } } }; int main() { vector< Vector3> vec(3); 面对 face.addVtx(vec [0]); face.setVtx(0,vec [0]) return 0; }

解决方案对于自动分配的对象使用 shared_ptr 。

通过给予 shared_ptr 一个不做任何事情的删除程序,并将你的 vtx 改为一个共享指针的向量到 const 向量。

将声明更改为

矢量< shared_ptr< Vector3 const> > vtx;

并添加如下指针:

vtx.push_back(shared_ptr 免责声明:未经过测试的代码,编译器不接触。

但是,除非你还要添加指向需要删除的向量的指针,只需使用一个原始指针的向量。或者,只是使用向量的向量,并复制数据中。

这不是一个好主意,使用raw指针持有所有权。对于使用智能指针。

但是相反,使用所有权智能指针来保存静态或自动对象的纯引用不是一个好主意。为此,使用原始指针或引用。

一般来说。

For the code below, I would like to know how to set std::shared_ptr to point the given objects in the two member functions. The Vector3 object which is allocated in the main function is not going to be deleted until the end of the program.

#include <memory> #include <vector> using std::vector; using std::shared_ptr; class Vector3 { // ... }; class Face { vector < shared_ptr <Vector3> > vtx; public: void addVtx (const Vector3& vt) { // vtx.push_back (); <-- how to push_back ? } void setVtx (const int v, const Vector3& vt) { if ( vtx.size() > 0 && v < vtx.size() ) { // vtx[v] = &vt; <-- how to assign ? } } }; int main () { vector <Vector3> vec (3); Face face; face.addVtx (vec[0]); face.setVtx (0, vec[0]) return 0; }

解决方案

There is not much point in using a shared_ptr for an automatically allocated object.

Technically you can do it, by giving the shared_ptr a deleter that doesn't do anything, and changing your vtx to be a vector of shared pointers to const vectors.

E.g. changing the declaration to

vector < shared_ptr <Vector3 const> > vtx;

and adding a pointer like this:

vtx.push_back( shared_ptr<Vector3 const>( &vt, [](Vector3 const*){} ) );

Disclaimer: untested code, not touched by a compiler.

However, unless you're going to also add pointers to vectors that need to be deleted, just use a vector of raw pointers. Or, just use a vector of vectors, and copy the in-data.

It's not a good idea to use raw pointers to hold ownership. For that use smart pointers.

But conversely, it's not a good idea to use ownership smart pointers to hold pure references to static or automatic objects. For that, use raw pointers or references.

In general.

更多推荐

将shared

本文发布于:2023-07-30 00:27:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:shared

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!