C++将局部变量添加到静态向量而不复制
C++ add local variables to static vector without copying
im 试图在 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.My 想法:
(不知何故,我必须使新运算符私有,或者只是在文档中说永远不要在组件上使用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个引用。销毁unique_ptr
时,将自动销毁组件对象。
这是使用内存分配,但对于 C# 也是如此。
请注意,与 C# 不同,在 C++ 中使用new
和delete
是一个坏主意,因为它们容易出现资源和内存泄漏。如果要在堆上创建对象,请改用shared_ptr
和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++的重要组成部分。但是你需要教育自己。
相关文章:
- 将指向给定子类的指针从一个向量复制到另一个向量
- 将字符向量复制到另一个向量
- 将shared_ptr的向量复制到抽象基的派生类
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 自定义类对象的C++向量 - 复制构造函数已删除 - std::ifstream
- 如何在C++中将一个对象从一个向量复制到另一个向量?
- 将特征向量复制到 C 数组
- 将std ::向量复制到CV :: Mat_的行操作相同
- 将向量复制到 std::string
- 如何以相反的顺序将整个向量复制到队列中
- 按索引将类类型元素从一个向量复制到另一个 c++
- 使用迭代器将向量复制到数组中
- 为什么是非法的:将指针向量复制到指向常量的指针向量中
- 将元素从一个向量复制到另一个向量的最有效方法,给定一个不被复制的索引列表
- C++-将数据从浮点向量复制到uint8向量
- 将字符串从向量复制到字符串
- 我可以使用STD ::复制将数据的位模式从整数向量复制到一系列未签名的字符
- 将指针从一个向量复制到另一个向量;地址指出了变化
- 如何将内容从一个字符串向量复制到另一个字符串向量
- 以相反的顺序将一个向量复制到另一个向量