I wrote an example which leads with Visual to a crash. I think the critical section is here:
A a;
B b(a);
pair p(a, b);
res.push_back(p);
I assign a temporary which takes a reference to another temporary and move it into a vector. I also noticed that the program seems not to crash with GCC. I think the problem is, that the reference is invalidated since the moment I move the objects into the vector. Do I have to use new
?
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
class Materials {
public:
Materials() = default;
};
class A {
private:
std::vector<Materials> _storage;
public:
void setStorage(const std::vector<Materials> &val) {
_storage = val;
}
};
class B {
private:
A &_a;
public:
B(A &foo) : _a(foo) {}
void run() {
std::vector<Materials> val;
for (int i = 0; i < 1000; i++) {
val.push_back(Materials());
}
_a.setStorage(val);
}
};
struct pair {
pair(const A &a, const B &b)
: _a(a)
, _b(b)
{
}
A _a;
B _b;
};
std::vector<pair> make_list() {
std::vector<pair> res;
for (int i = 0; i < 10; i++) {
A a;
B b(a);
pair p(a, b);
res.push_back(p);
}
return res;
}
int main()
{
std::vector<pair> list = make_list();
B &ref = list[1]._b;
ref.run();
}