使用std::vector构造一个对象并使用它

发布于 2024-10-02 16:58:31 字数 645 浏览 0 评论 0原文

我需要避免复制和破坏由 这个答案

现在我将它用作指针的 std::vector ,但我无法在不删除每个对象之前调用 std::vector::clear() ,也不能将 std::auto_ptr 与 std 容器一起使用。

我想做这样的事情:

vector<MyClass> MyVec;
MyVec.push_back();
MyClass &item = MyVec.back();

这将使用默认构造函数创建一个新对象,然后我可以获得引用并使用它。

关于这个方向有什么想法吗?

已解决:我使用 @MSalters 答案和 @Moo-Juices 建议使用 C++0x 右值引用来利用 std::move 语义。基于本文

I need to avoid the additional cost of copying and destructing the object contained by a std::vector caused by this answer.

Right now I'm using it as a std::vector of pointers, but I can't call std::vector::clear() without deleting each object before nor I can use std::auto_ptr with std containers.

I wanted to do something like this:

vector<MyClass> MyVec;
MyVec.push_back();
MyClass &item = MyVec.back();

This would create a new object with the default constructor and then I could get a reference and work with it.

Any ideas on this direction?

RESOLVED: I used @MSalters answer with @Moo-Juices suggestion to use C++0x rvalue references to take vantage of std::move semantics. Based on this article.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

最近可好 2024-10-09 16:58:31

Boost.PointerContainer 类将管理以下内存:你。特别参见 ptr_vector

通过容器 boost::ptr_vector,您可以使用 push_back(new T);,并且 T 元素的内存将被释放当容器超出范围时。

Boost.PointerContainer classes will manage the memory for you. See especially ptr_vector.

With the container boost::ptr_vector<T> you can use push_back(new T);, and the memory for T elements will get freed when the container goes out of scope.

樱&纷飞 2024-10-09 16:58:31

不存储对象,而是存储shared_ptr。这将避免对象复制,并在从向量中删除时自动销毁对象。

Instead of storing objects, store shared_ptr. This will avoid object copying, and will automatically destruct the object when removed from the vector.

幸福还没到 2024-10-09 16:58:31

快到了:

vector<MyClass> MyVec;
MyVec.push_back(MyClass()); // Any decent compiler will inline this, eliminating temporaries.
MyClass &item = MyVec.back();

Almost there:

vector<MyClass> MyVec;
MyVec.push_back(MyClass()); // Any decent compiler will inline this, eliminating temporaries.
MyClass &item = MyVec.back();
帅冕 2024-10-09 16:58:31

您可以通过调整大小来完成此操作,这将默认构造它必须添加到向量中的任何其他对象:

vector MyVec;
MyVec.resize(MyVec.size() + 1);
MyClass &item = MyVec.back();

但请考虑为什么需要这样做。分析是否确实表明复制对象的成本太高?它们是不可复制的吗?

You can do this with resize, which will default construct any additional objects it has to add to the vector:

vector MyVec;
MyVec.resize(MyVec.size() + 1);
MyClass &item = MyVec.back();

But do consider why you need to do this. Has profiling really shown that it's too expensive to copy the objects around? Are they non-copyable?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文