Similar but different to what others have said about using std::reference_wrapper<T>
This maybe of use, but someone has also mentioned this in the comments below your question and that is using smart pointers, the only difference here is that I happen to take it a step farther by creating a template wrapper class. Here is the code and it should do what you are looking for except for this is working on the heap instead of using references.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Car {
public:
std::string color;
std::string name;
Car(){} // Added Default Constructor to be safe.
Car( std::string colorIn, std::string nameIn ) : color( colorIn ), name( nameIn ){}
};
template<class T>
class Wrapper {
public:
std::shared_ptr<T> ptr;
explicit Wrapper( T obj ) {
ptr = std::make_shared<T>( T( obj ) );
}
~Wrapper() {
ptr.reset();
}
};
int main () {
std::vector<Wrapper<Car>> collection1;
std::vector<Wrapper<Car>> collection2;
collection1.emplace_back( Car("black", "Ford") );
collection1.emplace_back( Car("white", "BMW") );
collection1.emplace_back( Car("yellow", "Audi") );
collection2.push_back( collection1[0] );
std::cout << collection2[0].ptr->color << " " << collection2[0].ptr->name << std::endl;
collection2[0].ptr->color = std::string( "green" );
collection2[0].ptr->name = std::string( "Gremlin" );
std::cout << collection1[0].ptr->color << " " << collection1[0].ptr->name << std::endl;
return 0;
}
If you noticed in the code I changed collection 2's first index object's fields and then I printed out collection 1's first index object's fields and they were changed. So what happens in one collection will happen in another because they are shared memory
by using std::shared_ptr<T>
the only reason I put it in the wrapper is so that its constructor will make new memory for you upon construction so that you wouldn't have to do this every time; the template wrapper class does this for you and you don't have to worry about cleaning up the memory because std::shared_ptr<T>'s destructor
should do that for you, but to be safe I did call the shared_ptr<T>'s release method
in the Wrapper's destructor
.
To make this a little cleaner or more readable you can do this instead:
typedef Wrapper<Car> car;
std::vector<car> collection1;
std::vector<car> collection2;
// rest is same
And it will do the same for you.
Now if you don't want to use pointers or the heap you could create another wrapper yourself which would be similar to std::refrence_wrapper<T>
you can write your own template wrapper for references that is very simple to use. Here is an example:
template<class T>
class Wrapper2 {
public:
T& t;
explicit Wrapper2( T& obj ) : t(obj) {}
};
Then in your source you would do the same as above and it still works
typedef Wrapper2<Car> car2;
std::vector<car2> coll1;
std::vector<car2> coll2;
coll1.emplace_back( Car( "black", "Ford" ) );
coll1.emplace_back( Car( "white", "BMW" ) );
coll1.emplace_back( Car( "yellow", "Audi" ) );
coll2.push_back( coll1[0] );
std::cout << coll2[0].t.color << " " << coll2[0].t.name << std::endl;
coll2[0].t.color = std::string( "brown" );
coll2[0].t.name = std::string( "Nova" );
std::cout << coll1[0].t.color << " " << coll1[0].t.name << std::endl;
And by modifying coll2's first indexed object's fields, coll1's first indexed object's fields are being changed as well.
EDIT
@Caleth asked me this in the comments:
What benefit is Wrapper over just shared_ptr here? (and Wrapper2 over reference_wrapper)
Without this wrapper look at this code here:
class Blob {
public:
int blah;
Blob() : blah(0) {}
explicit Blob( int blahIn ) : blah( blahIn ) {}
};
void someFunc( ... ) {
std::vector<std::shared_ptr<Blob>> blobs;
blobs.push_back( std::make_shared<Blob>( Blob( 1 ) ) );
blobs.push_back( std::make_shared<Blob>( Blob( 2 ) ) );
blobs.push_back( std::make_shared<Blob>( Blob( 3 ) ) );
}
Yeah it is readable but a lot of repetitious typing, now with the wrapper
void someFunc( ... ) {
typedef Wrapper<Blob> blob;
std::vector<blob> blobs;
blobs.push_back( Blob( 1 ) );
blobs.push_back( Blob( 2 ) );
blobs.push_back( Blob( 3 ) );
}
Now as for the Wrapper to just a reference; try doing this:
void someFunc( ... ) {
std::vector<int&> ints; // Won't Work
}
However creating a class template
that stores a reference
to obj T
you can now do this:
void someFunc( ... ) {
typedef Wrapper2<Blob> blob;
std::vector<blob> blobs;
blobs.push_back( Blob( 1 ) );
blobs.push_back( Blob( 2 ) );
// then lets create a second container
std::vector<blob> blobs2;
// Push one of the reference objects in container 1 into container two
blobs2.push_back( blobs[0] );
// Now blobs2[0] contains the same referenced object as blobs[0]
// blobs[0].t.blah = 1, blobs[1].t.blah = 2 and blobs2[0].t.blah = 1
// lets change blobs2[0].t.blah value
blobs2[0].t.blah = 4;
// Now blobs1[0].t.blah also = 4.
}
You couldn't do this before with references in std::vector<T>
unless if you used std::reference_wrapper<T>
which does basically the same thing but much more convoluted. So for simple objects having your own wrappers can come in handy.
EDIT - Something that I had overlooked and didn't catch this when working in my IDE because everything compiled, built and ran successfully but it has come to my attention that the OP of this question should completely disregard my second wrapper. This can lead to Undefined Behavior. So you can still use the 1st wrapper of the smart pointer or if you need storable references as others had already pointed out definitely use std::some_container<std::reference_wrapper<T>>
. I will leave the existing code above for a historical reference for others to learn from. I do thank those involved into pointing out the Undefined Behavior. And for those who don't know please take into consideration that I have no formal training and that I'm 100% self taught and still learning. You can also refer to this question that I had asked concerning references and undefined behavior here: undefined behavior of references on stack
Conclusion
Trying to use references of the same objects in multiple containers can be a bad idea because it can lead to Undefined Behavior when something is added or removed from either container leaving dangling references. So the proper or safer choice would be to use std::shared_ptr<T>
to achieve the functionality that you want.
There is nothing wrong with using references but special care and design does need to be taken into consideration especially about the lifetime of the objects that are being referenced. If the objects are moved and then the reference is being accessed afterwards this will lead to problems, but if you know the lifetime of the object and that it will not be moved or destroyed, then accessing the references is not a problem. I'd still suggest using std::shared_ptr
or std::reference_wrapper
std::vector<std::shared_ptr<Car>>
, then you get what you want. – Mine Jan 5 '17 at 6:18->
looks like.
. (Python pointers are "smart" (garbage-collected) and you need to use smart pointers in C++ too, but this is a minor detail). – n. 'pronouns' m. Jan 5 '17 at 6:30reference_wrapper
.) – juanchopanza Jan 5 '17 at 7:09