ist hier ein Code-Schnipsel:Wird das Erstellen einer Klassenvorlage-Wrapper einer Referenz Ursache undefined Behavoir verursachen?
#include <iostream>
#include <string>
#include <vector>
template<class T>
class Wrapper {
public:
T& t;
explicit Wrapper2(T& obj) : t(obj) {}
};
class Car {
public:
std::string color;
std::string name;
Car(){}
Car(std::string colorIn, std::string nameIn) : color(colorIn), name(nameIn){}
};
int _tmain(int iNumArguments, _TCHAR* pArgumentText[]) {
typedef Wrapper<Car> car;
// Create 2 Containers
std::vector<car> collection1;
std::vector<car> collection2;
// Populate collection 1 with reference objects
collection1.push_back(Car("black", "Ford"));
collection1.push_back(Car("white", "BMW"));
collection1.push_back(Car("yellow", "Audi"));
// use referenced object at index 0 in collection 1
// to populate index 0 of collection 2
collection2.push_back(collection1[0]);
// Print Out index 0 of collection2's referenced object's fields
std::cout << collection2[0].t.color << " " << collection2[0].t.name << std::endl;
// Change collection2's index 0 referenced object's fields
collection2[0].t.color = std::string("green");
collection2[0].t.name = std::string("Gremlin");
// Print out collection1's index 0 referenced object's fields
// and they are changed
std::cout << collection1[0].ptr->color << " " << collection1[0].ptr->name << std::endl;
return 0;
}
Dies kompiliert, bauen und ohne Fehler erfolgreich in MSVS2015 CE laufen.
Kann dies oder kann dies Undefined Behavior generieren und wenn ja; Wie?
Sie wollen wahrscheinlich [ 'std :: reference_wrapper'] (http://en.cppreference.com/w/ cpp/utility/functional/reference_wrapper) –
@VittorioRomeo Ich weiß über 'std :: reference_wrapper' Ich wollte nur wissen, ob dies zu undefiniertem Verhalten führen würde. –
Sie baden in UB, weil Sie Verweise auf Provisorien speichern und später verwenden. – Quentin