c++ - C ++将局部变量添加到静态向量而不复制
问题描述
我试图在 C++ 中归档以下内容:我希望能够创建局部变量,将它们添加到全局静态向量中,并且只应将指向它们的指针添加到向量中。
在 C# 中,我能够编写(示例):
public static List<Component> CACHE = new List<Component>(); //Somewere in class
//Now in method:
Component a = new Component();
a.Name = "Noël";
CACHE.Add(a); //Adds reference to CACHE a without copy
在 C++ 中,我看到了 2 个解决方案:
1.使用动态分配:
static std::vector<Component*> CACHE; //Somewere in class
//Now in method:
Component* a = new Component();
a->Name = L"Noël";
CACHE.push_back(a);
问题是我不想使用动态分配,因为它很慢。
2.我的想法:
(不知何故,我必须将 new 运算符设为私有,或者只是在文档中说永远不要在组件上使用 new )
//somewere hidden:
std::vector<Component*> GLOBAL_CACHE;
//In method dont use new, instead we use a custom global function
Component* a = CREATE_COMPONENT();
static std::vector<Component*> CACHE; //Example
Component& ExampleRef;//Example
a->Name = L"Noël";
CACHE.push_back(a);
ExampleRef = *a;
现在 CREATE_COMPONENT():
Component* CREATE_COMPONENT()
{
GLOBAL_CACHE.push_back(Component()); //Add empty component
return &GLOBAL_CACHE[GLOBAL_CACHE.size() - 1]; //return pointer to construct added above. I think we now have everything on the stack and we just send around pointers to the stack object
}
我的想法值得,甚至可行吗?还是我应该只使用动态分配?
解决方案
由于垃圾收集,在 C++ 中做同样的事情是不可能的。但是您可以通过使用shared_ptr<Component>
向量的元素类型来进行类似的操作:
#include <memory>
std::vector<std::shared_ptr<Component>> CACHE;
// ...
auto a = std::make_shared<Component>();
a->Name = "Noël";
CACHE.push_back(a);
当不再引用该组件时,该组件将被自动销毁。
如果您不打算将指针的副本存储在其他地方,但这CACHE
是您放置它们的唯一地方,那么您可以unique_ptr
改用:
#include <memory>
std::vector<std::unique_ptr<Component>> CACHE;
// ...
CACHE.push_back(std::make_unique<Component>());
CACHE.back()->Name = "Noël";
与 不同shared_ptr
,unique_ptr
不能复制,只能移动,这意味着只能有 1 个引用。Component 对象在销毁时会自动unique_ptr
销毁。
这是使用内存分配,但对于 C# 也是如此。
请注意,与 C# 不同,在 C++ 中使用new
anddelete
不是一个好主意,因为它们容易发生资源和内存泄漏。如果要在堆上创建对象,请使用shared_ptr
and 。unique_ptr
最后,您应该阅读“C++ 移动语义”。你不需要避免把东西放在堆栈上。您可以移动对象而不是复制它们。例子:
#include <memory>
std::vector<Component> CACHE;
// ...
Component a;
a.Name = "Noël";
CACHE.push_back(std::move(a)); // No copy. The 'a' variable can no longer be used.
移动有时是自动的,它们是 C++ 的重要组成部分。但是您需要对此进行自我教育。
推荐阅读
- gcc - GCC 的 sum += 1..n 的自动矢量化 SSE2 实现到底在做什么?
- .net - 通过登录在 WebBrowser 控件中显示 MediaWiki 页面
- python - Django 教程错误:“/admin/ 处的 TypeError - 'set' 对象不可逆”
- python - 重启 Jupyter notebook 后数据丢失
- c++ - gcc size_t 和 sizeof 算术转换为 int
- go - Go 所有的 goroutines 都睡着了死锁
- javascript - Firefox 和 Chrome 中的 css-grid 渲染不同
- python - 在 Python 中使用外部数据文件进行单元测试
- r - 如何使用 dplyr 将顺序标识分配给二进制状态?
- discord - 如何对机器人进行编程以检查用户是否在特定网站上?