ローカル変数で満たされたベクトルを返すのは安全ですか?例えばローカル変数を含むベクトルを返すのは安全ですか?
は、私が持っている場合は...この例では
#include <vector>
struct Target
{
public:
int Var1;
// ... snip ...
int Var20;
};
class Test
{
public:
std::vector<Target> *Run(void)
{
std::vector<Target> *targets = new std::vector<Target>;
for(int i=0; i<5; i++) {
Target t = Target();
t.Var1 = i;
// ... snip ...
t.Var20 = i*2; // Or some other number.
targets->push_back(t);
}
return targets;
}
};
int main()
{
Test t = Test();
std::vector<Target> *container = t.Run();
// Do stuff with `container`
}
は、私は、ベクターにそれらをプッシュし、それへのポインタを返す、forループ内で複数Target
のインスタンスを作成しています。 Target
インスタンスはスタックにローカルに割り当てられているため、スタック上のオブジェクト(間もなく上書きされるなど)を参照しているため、返されたベクトルが安全でないことを意味しますか?もしそうなら、ベクトルを返すための推奨される方法は何ですか?
私はこれをC++で書いています。
[C++でのベクトルの動的メモリ割り当て]の複製が可能です(http://stackoverflow.com/questions/9252523/dynamic-memory-allocation-of-vectors-in-c) –