C++将局部变量添加到静态向量而不复制

C++ add local variables to static vector without copying

本文关键字:向量 复制 静态 局部变量 添加 C++      更新时间:2023-10-16

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++ 中使用newdelete是一个坏主意,因为它们容易出现资源和内存泄漏。如果要在堆上创建对象,请改用shared_ptrunique_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++的重要组成部分。但是你需要教育自己。