c++ - 实例如何将自身添加到 vector 中?

标签 c++ c++11 vector

我需要实例化一个 SpriteWithTimer 类,并且新对象将其自身添加到 vector vsprites 中。

这是一个代码片段:

#include <vector>
...
class SpriteWithTimer {
   public:
   SpriteWithTimer();
   ~SpriteWithTimer();
   ...
};
static std::vector<SpriteWithTimer> vsprites;

int main()
{
   ...
}
...
SpriteWithTimer::SpriteWithTimer(){
        ...
        vsprites.push_back(this);
   };

但我得到了他的错误:

no matching function for call to ‘std::vector<SpriteWithTimer>::push_back(SpriteWithTimer*)’
no instance of overloaded function "std::vector<_Tp, _Alloc>::push_back [with _Tp=SpriteWithTimer, _Alloc=std::allocator<SpriteWithTimer>]" matches the argument list -- argument types are: (SpriteWithTimer *) -- object type is: std::vector<SpriteWithTimer, std::allocator<SpriteWithTimer>>

谢谢!

最佳答案

存储在 vector 中的对象始终是一个全新的单独构造的对象。因此,您无法将在其他地方创建的对象存储到 vector 。或者,您可以存储:

  1. 该对象的拷贝:push_back(*this),
  2. 一个对象,内容已从该对象移走:push_back(std::move(*this)),
  3. 指向该对象的指针 push_back(this)

您需要选择适合您情况的内容。在第三种情况下,请注意悬空指针。基本上,您应该保证所指向对象的生命周期在使用这些指针之前不会结束。

关于c++ - 实例如何将自身添加到 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64800553/

相关文章:

c++ - 默认创建类 `final`还是给它们一个虚拟的析构函数?

python - 如何在 Python 中找到两个向量具有相等元素的索引集

c++ - 多维 vector 和指向 vector 的指针

c++ - 使用 NAN 在 Node.js 的 C++ 模块中未调用 SetAccessor 函数

c++ - 继承到派生类的基构造函数?

c++ - 将 weak_ptr 与原始指针进行比较不起作用,正在寻找替代方案

c++ - 从文本文件C++填充对象

c++ - 将成员函数转换为指向成员函数的指针

c++ - 在屏幕上绘制图像后背景发生变化

c++ - 重载 [] 和 , c++11