自大學以來沒有使用C++後,我試圖使用具有兩種類型的子對象的向量,而且我顯然得到了一些錯誤。包含多態對象的向量:靜態斷言錯誤
最初我使用了一個可以工作的指針向量,但是如果我理解正確,那麼在清除時會泄漏內存。
我得到的錯誤導致我相信它與類中的靜態計數器有關(與最後一個成員一起銷燬?),但刪除並沒有解決它。
錯誤會導致在此,在stl_construct.h:
#if __cplusplus >= 201103L
// A deleted destructor is trivial, this ensures we reject such types:
static_assert(is_destructible<_Value_type>::value,
"value type is destructible");
#endif
嗯,好吧,但我的析構函數都明確聲明。我記得父類應該使用虛擬析構函數並修復它,但問題依然存在。
將構造函數/析構函數移到公共虛擬父類上不應該(事實上也沒有)改變它。
現在我假設我以某種方式濫用向量。這是我的例子:
主:
#include <stdio.h>
#include "Foo.h"
#include <iostream>
Bar buildBar();
int main(int argc, char **argv)
{
std::vector<Foo> Foos;
Foos.reserve(1);
Foos.push_back(buildBar());
for (int idx=(0);sizeof(Foos);idx++)
{
try {
std::cout << "x = " << Foos.at(idx).getLoc().at(0);
}
catch (std::exception& e) {
std::cout << idx << ": Index out of range" << std::endl;
}
}
Foos.clear();
return 0;
}
Bar buildBar()
{
Bar* temp = new Bar(5,6);
return *temp;
}
foo.h中,用構造移到頭:
#ifndef FOO_H
#define FOO_H
#include <vector>
class Foo
{
public:
//int maxoID(){return lastoID;} //0-indexed
/* Other things */
virtual std::vector<int> getLoc(){ return {x_Base,y_Base};}
Foo():
//oID(-1),
x_Base(-1),
y_Base(-1){}
virtual ~Foo(){}
protected:
int x_Base;
int y_Base;
};
class Bar : public Foo
{
public:
Bar(int x1, int y1):
x_End(-1),
y_End(-1)
{
x_Base = x1;
y_Base = y1;
}
~Bar(){}
std::vector<int> getLoc() {return {x_Base,y_Base,x_End,y_End};}
protected:
int x_End;
int y_End;
};
#endif // FOO_H
你'buildBar()'函數是內存泄漏的向量提取的元素。 – juanchopanza
「_Initially我使用了一個向量指針,它的工作,但如果我理解正確,這將在清除時泄漏內存。」所以,爲什麼不使用'std :: unique_ptr'的std :: vector?相關閱讀:[什麼是對象切片?](https://stackoverflow.com/questions/274626/what-is-object-slicing) –
'sizeof(Foos)'不會告訴你向量中有多少項。 (它會告訴你它佔用了多少字節,但不包含它所包含的數據)。 – Galik