首页 > 解决方案 > 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++

解决方案


由于垃圾收集,在 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_ptrunique_ptr不能复制,只能移动,这意味着只能有 1 个引用。Component 对象在销毁时会自动unique_ptr销毁。

这是使用内存分配,但对于 C# 也是如此。

请注意,与 C# 不同,在 C++ 中使用newanddelete不是一个好主意,因为它们容易发生资源和内存泄漏。如果要在堆上创建对象,请使用shared_ptrand 。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++ 的重要组成部分。但是您需要对此进行自我教育。


推荐阅读