How to use multiple pointers to an object by vector/map - c++

I have a question about using multiple pointers to an object.
I have a pointer in a vector and another one in a map.
The map uses the vector to index the object. Example code:
class Thing
{
public:
int x = 1;
};
Thing obj_Thing;
std::vector<Thing*> v_Things;
v_Things.push_back(&obj_Thing);
std::map<int, Thing*> m_ThingMap;
m_ThingsMap[v_Things[0]->x] = v_Things[0]; // crucial part
is it good practice to assign pointers to each other like this?
Should the vector and/or map hold addresses instead? Or should I be using a pointer to pointer for the map?

It all depends on what you want to do.
However, your approach can get really hairy when your project grows, and especially when others contribute to it.
To start with, this:
m_ThingsMap[v_Things[0]->x] = v_Things(0);
should be:
m_ThingsMap[v_Things[0]->x] = v_Things[0];
Moreover, storing raw pointers in a std::vector is possible, but needs special care, since you may end up with dangling pointers, if the object that a pointer points to gets deallocated too soon.
For that I suggest you to use std::weak_ptr, like this:
std::vector<std::weak_ptr<Thing>> v_Things;
in case you decide to stick with that approach (I mean if the pointer points to an object that is pointer-shared from another pointer).
If I were you, I would redesign my approach, since your code is not clean enough, let alone your logic; it takes one moment or two for someone to understand what is going on with all the pointers and shared places.

Related

C++ several instances (but not all) of a class sharing a vector

I want to have a class C, such that instances of C hold a std::vector<int> as a private member. Now many instances (but not all) of C will share that vector and keeping a copy for each instance is what I would want to avoid.
If this vector were a single integer for example, I could create a template class for C and have it like this:
template <int N>
class C {
// something
};
If instead of some instances I wanted all instances to share that vector then I would declare the variable static as
class C {
static std::vector<int> _vec;
What I am looking is for something intermediate. I could for example keep a shared_ptr as a private non-static member as in
class C {
std::shared_ptr<std::vector<int>> _vec;
}
And that would take care of the lifetime of the object, with some overhead for maintaining shared ownership and also an extra pointer per-instance. I could keep a reference instead and let the creator of the instances take care of the lifetime, but avoid the overhead of the shared_ptr. Is there a better approach to this design question?
…such that instances of C hold a std::vector as a private member. Now many instances (but not all) of C will share that vector
So, that's self-contradicting. You can't hold an instance and share the instance safely.
This is a classical use case of pointers; even more specifically, classical use case of a shared pointer, as you already noticed.
I could keep a reference instead and let the creator of the instances take care of the lifetime,
/me sounds the access-after-destruction alarm You're about to find out that won't work. The lifetime is not like you think, but ends when the owning object's lifetime ends. So, this breaks. (Also, you'll find that under the hood, handing out references compiles down to the same code as handing out raw pointers – it's just safer and does the dereferencing automagically within the language; you're not actually saving a memory indirection there. The classes containing the reference still need to know the address of the object they're handling, and that's the same as having a pointer, if you ask your CPU.)
It breaks, unless the thing handing out the references keeps a count on how many references it handed out, subtracts many references it handed out belong to C instances that were deconstructed, and then deconstructs the vector as soon as that number reaches 0. Take a wild guess what a shared_ptr does! Exactly this reference counting.
Often, however, the access logic is easier; for example,
I have a vector of C, std::vector<C> lexicon, and all held C._vec need to get removed exactly when that full lexicon goes out of scope, so I handle that manually
actually doesn't need reference counting and hence is lower-overhead. You can indeed solve that by handing out references – but I'd actually prefer to hand out raw pointers in that case: they just as much don't imply ownership, and you don't accidentally make a copy of the std::vector<int> when you pass the pointer by value.
If your lifetime tracking isn't as easy as that example :
There's no magic usage tracking in references; and you need something to keep track of whether something is still holding some handle to your individual vector. That tracking is exactly the "overhead" shared_ptr incurs. No way around it.
A private shared_ptr is hence the right approach:
class C {
private:
std::shared_ptr<std::vector<int>> _vec;
}
Your static approach takes you nowhere here - it only makes sense if all, and really all, instances share the same vector which should essentially live from the beginning of time till the end, and even then, it's a bit of a solution that can lead to additional headaches in form of the static initialization order fiasco. I'd advise to not do that under almost all circumstances.
(Plus, a static member also just boils down to the code looking up the same address – so, performance-wise, same as a pointer. Again, nothing really won here.)

shared_ptr in vector trouble - iterating and losing scope - getting corrupted data

I'm not new to C++ but I do mostly work in C# and other managed languages usually so I'm not that well versed in shared pointers etc.
I basically have a 3-dimensional map of shared_ptrs to objects of a custom class (for 3d purposes).
These shared_ptrs live inside the map and are referenced all over the project, so far so good. For a specific piece of functionality I store some of these shared_ptrs in a vector to be iterated over later in the code but this is where things seem to break down.
Say I have 100 of these objects with their pointers stored in the 3d map and 3 of them are added to the vector because they have special properties for functionality. When I'm traversing the vector I call functions on these 3 objects. This all works fine until the for loop (for the iteration) hits it's second run on element [1] of the vector, at this point element [0] is full of corrupted data (but element[1] needs to access element[0] to perform one of the functions) and this is where I get an error.
As I said, I'm not that well versed in shared_ptrs but I thought that the data wouldn't be corrupted because the actual object is created in the creation of the 3-dimensional map - also, the vector hasn't gone out of scope yet because I am only in the 2nd run through the for loop (with 3 objects and so 3 iterations).
I know I must be doing something wrong but I have no idea how to debug this further - basically when I step through the code and it comes to the 2nd run of the for loop, if I look at element [0]'s shared_ptr in the vector (using VS) it is all corrupted.
Here is the loop of the code so you can see. The vector is created in the constructor of the class this code is in and the map (where the shared_ptrs and objects are created) is in the main class of the application. Also, getAdjacent takes objA and objB as pointers and so "fills" objB with the data of the adjacent object to objA:
for(vector<shared_ptr<ObjectClass>>::iterator iterator = objects.begin(); iterator != objects.end(); iterator++)
{
shared_ptr<ObjectClass> objA = (shared_ptr<ObjectClass>) iterator->get();
shared_ptr<ObjectClass> objB;
m_3DMap->getAdjacent(objA, objB);
objA->move(objB);
}
Could it be something to do with the cast I perform on iterator->get()? I couldn't see any other way to do it because if I don't have that cast there VS says that it can't convert from ObjectClass* to shared_ptr which is confusiong to me too because I thought I have a vector of shared_ptrs?..
Thanks for your time and it would be great if anyone could help.
For starters, you should call get() on a shared_ptr very rarely. And using that pointer to init another shared_ptr you MUST NOT do, ever.
The raw pointer you construct the smart pointer from is passed for ownership. And ownership must be exclusive. The way you use it two shared_ptrs will own the same object resulting a premature, and later a double delete at some point, both putting you to UB land.
This is somewhat better than your original, but without seeing code chances are good that getAdjacent is also broken in some way.
for(auto i = objects.begin(); i != objects.end(); ++i)
{
const auto& objA = *i;
shared_ptr<ObjectClass> objB;
m_3DMap->getAdjacent(objA, objB);
objA->move(objB);
}
signature of getAdjacent should be something like
void getAdjacent(shared_ptr<ObjectClass> const& objA, shared_ptr<ObjectClass>& objB);
to have fighting chance.
Okay I found the problem I had.
It was in part to do with what Balog Pal said about putting the shared_ptrs in a vector even though they live in a map so I changed this so that the vector held pointers to the shared_ptrs. Although this may still be bad practice, it got around the issue - especially as the vector was local and lost scope after the function exited.
The original vector approach was implemented as I was getting a dereference on my map iterator somewhere in the function and so I decide to leave all map manipulation outside the iterating (hence storing the 'special' objects in the vector to be iterated over later).
I have now changed the implementation to get rid of this inefficiency as my manipulation functions now return a new map iterator and thus negating the problem.
It would have been nice if the error message was somewhat more helpful that it was because it took me some time to realize the iterator became invalidated because I had an insert() buried in one of the functions that was called on the 'special' objects.
Although this answer doesn't really answer the exact question I asked, it answers the problem as a whole and why I designed the function in the way I did in the question.
Thanks for the help Balog and itwasntpete for the answers and comments.

Array: Storing Objects or References

As a Java developer I have the following C++ question.
If I have objects of type A and I want to store a collection of them in an array,
then should I just store pointers to the objects or is it better to store the object itself?
In my opinion it is better to store pointers because:
1) One can easily remove an object, by setting its pointer to null
2) One saves space.
Pointers or just the objects?
You can't put references in an array in C++. You can make an array of pointers, but I'd still prefer a container and of actual objects rather than pointers because:
No chance to leak, exception safety is easier to deal with.
It isn't less space - if you store an array of pointers you need the memory for the object plus the memory for a pointer.
The only times I'd advocate putting pointers (or smart pointers would be better) in a container (or array if you must) is when your object isn't copy construable and assignable (a requirement for containers, pointers always meet this) or you need them to be polymorphic. E.g.
#include <vector>
struct foo {
virtual void it() {}
};
struct bar : public foo {
int a;
virtual void it() {}
};
int main() {
std::vector<foo> v;
v.push_back(bar()); // not doing what you expected! (the temporary bar gets "made into" a foo before storing as a foo and your vector doesn't get a bar added)
std::vector<foo*> v2;
v2.push_back(new bar()); // Fine
}
If you want to go down this road boost pointer containers might be of interest because they do all of the hard work for you.
Removing from arrays or containers.
Assigning NULL doesn't cause there to be any less pointers in your container/array, (it doesn't handle the delete either), the size remains the same but there are now pointers you can't legally dereference. This makes the rest of your code more complex in the form of extra if statements and prohibits things like:
// need to go out of our way to make sure there's no NULL here
std::for_each(v2.begin(),v2.end(), std::mem_fun(&foo::it));
I really dislike the idea of allowing NULLs in sequences of pointers in general because you quickly end up burying all the real work in a sequence of conditional statements. The alternative is that std::vector provides an erase method that takes an iterator so you can write:
v2.erase(v2.begin());
to remove the first or v2.begin()+1 for the second. There's no easy "erase the nth element" method though on std::vector because of the time complexity - if you're doing lots of erasing then there are other containers which might be more appropriate.
For an array you can simulate erasing with:
#include <utility>
#include <iterator>
#include <algorithm>
#include <iostream>
int main() {
int arr[] = {1,2,3,4};
int len = sizeof(arr)/sizeof(*arr);
std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// remove 2nd element, without preserving order:
std::swap(arr[1], arr[len-1]);
len -= 1;
std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// and again, first element:
std::swap(arr[0], arr[len-1]);
len -= 1;
std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
preserving the order requires a series of shuffles instead of a single swap, which nicely illustrates the complexity of erasing that std::vector faces. Of course by doing this you've just reinvented a pretty big wheel a whole lot less usefully and flexibly than a standard library container would do for you for free!
It sounds like you are confusing references with pointers. C++ has 3 common ways of representing object handles
References
Pointers
Values
Coming from Java the most analogous way is to do so with a pointer. This is likely what you are trying to do here.
How they are stored though has some pretty fundamental effects on their behaviors. When you store as a value you are often dealing with copies of the values. Where pointers are dealing with one object with multiple references. Giving a flat answer of one is better than the other is not really possible without a bit more context on what these objects do
It completely depends on what you want to do... but you're misguided in some ways.
Things you should know are:
You can't set a reference to NULL in C++, though you can set a pointer to NULL.
A reference can only be made to an existing object - it must start initialized as such.
A reference cannot be changed (though the referenced value can be).
You wouldn't save space, in fact you would use more since you're using an object and a reference. If you need to reference the same object multiple times then you save space, but you might as well use a pointer - it's more flexible in MOST (read: not all) scenarios.
A last important one: STL containers (vector, list, etc) have COPY semantics - they cannot work with references. They can work with pointers, but it gets complicated, so for now you should always use copyable objects in those containers and accept that they will be copied, like it or not. The STL is designed to be efficient and safe with copy semantics.
Hope that helps! :)
PS (EDIT): You can use some new features in BOOST/TR1 (google them), and make a container/array of shared_ptr (reference counting smart pointers) which will give you a similar feel to Java's references and garbage collection. There's a flurry of differences but you'll have to read about it yourself - they are a great feature of the new standard.
You should always store objects when possible; that way, the container will manage the objects' lifetimes for you.
Occasionally, you will need to store pointers; most commonly, pointers to a base class where the objects themselves will be of different types. In that case, you need to be careful to manage the lifetime of the objects yourself; ensuring that they are not destroyed while in the container, but that they are destroyed once they are no longer needed.
Unlike Java, setting a pointer to null does not deallocate the object pointed to; instead, you get a memory leak if there are no more pointers to the object. If the object was created using new, then delete must be called at some point. Your best options here are to store smart pointers (shared_ptr, or perhaps unique_ptr if available), or to use Boost's pointer containers.
You can't store references in a container. You could store (naked) pointers instead, but that's prone to errors and is therefore frowned upon.
Thus, the real choice is between storing objects and smart pointers to objects. Both have their uses. My recommendation would be to go with storing objects by value unless the particular situation demands otherwise. This could happen:
if you need to NULL out the object without removing it from the
container;
if you need to store pointers to the same object in
multiple containers;
if you need to treat elements of the container
polymorphically.
One reason to not do it is to save space, since storing elements by value is likely to be more space-efficient.
To add to the answer of aix:
If you want to store polymorphic objects, you must use smart pointers because the containers make a copy, and for derived types only copy the base part (at least the standard ones, I think boost has some containers which work differently). Therefore you'll lose any polymorphic behaviour (and any derived-class state) of your objects.

C++: What are scenarios where using pointers is a "Good Idea"(TM)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Common Uses For Pointers?
I am still learning the basics of C++ but I already know enough to do useful little programs.
I understand the concept of pointers and the examples I see in tutorials make sense to me. However, on the practical level, and being a (former) PHP developer, I am not yet confident to actually use them in my programs.
In fact, so far I have not felt the need to use any pointer. I have my classes and functions and I seem to be doing perfectly fine without using any pointer (let alone pointers to pointers). And I can't help feeling a bit proud of my little programs.
Still, I am aware that I am missing on one of C++'s most important feature, a double edged one: pointers and memory management can create havoc, seemingly random crashes, hard to find bugs and security holes... but at the same time, properly used, they must allow for clever and efficient programming.
So: do tell me what I am missing by not using pointers.
What are good scenarios where using pointers is a must?
What do they allow you to do that you couldn't do otherwise?
In which way to they make your programs more efficient?
And what about pointers to pointers???
[Edit: All the various answers are useful. One problem at SO is that we cannot "accept" more than one answer. I often wish I could. Actually, it's all the answers combined that help to understand better the whole picture. Thanks.]
I use pointers when I want to give a class access to an object, without giving it ownership of that object. Even then, I can use a reference, unless I need to be able to change which object I am accessing and/or I need the option of no object, in which case the pointer would be NULL.
This question has been asked on SO before. My answer from there:
I use pointers about once every six lines in the C++ code that I write. Off the top of my head, these are the most common uses:
When I need to dynamically create an object whose lifetime exceeds the scope in which it was created.
When I need to allocate an object whose size is unknown at compile time.
When I need to transfer ownership of an object from one thing to another without actually copying it (like in a linked list/heap/whatever of really big, expensive structs)
When I need to refer to the same object from two different places.
When I need to slice an array without copying it.
When I need to use compiler intrinsics to generate CPU-specific instructions, or work around situations where the compiler emits suboptimal or naive code.
When I need to write directly to a specific region of memory (because it has memory-mapped IO).
Pointers are commonly used in C++. Becoming comfortable with them, will help you understand a broader range of code. That said if you can avoid them that is great, however, in time as your programs become more complex, you will likely need them even if only to interface with other libraries.
Primarily pointers are used to refer to dynamically allocated memory (returned by new).
They allow functions to take arguments that cannot be copied onto the stack either because they are too big or cannot be copied, such as an object returned by a system call. (I think also stack alignment, can be an issue, but too hazy to be confident.)
In embedded programing they are used to refer to things like hardware registers, which require that the code write to a very specific address in memory.
Pointers are also used to access objects through their base class interfaces. That is if I have a class B that is derived from class A class B : public A {}. That is an instance of the object B could be accessed as if it where class A by providing its address to a pointer to class A, ie: A *a = &b_obj;
It is a C idiom to use pointers as iterators on arrays. This may still be common in older C++ code, but is probably considered a poor cousin to the STL iterator objects.
If you need to interface with C code, you will invariable need to handle pointers which are used to refer to dynamically allocated objects, as there are no references. C strings are just pointers to an array of characters terminated by the nul '\0' character.
Once you feel comfortable with pointers, pointers to pointers won't seem so awful. The most obvious example is the argument list to main(). This is typically declared as char *argv[], but I have seen it declared (legally I believe) as char **argv.
The declaration is C style, but it says that I have array of pointers to pointers to char. Which is interpreted as a arbitrary sized array (the size is carried by argc) of C style strings (character arrays terminated by the nul '\0' character).
If you haven't felt a need for pointers, I wouldn't spend a lot of time worrying about them until a need arises.
That said, one of the primary ways pointers can contribute to more efficient programming is by avoiding copies of actual data. For example, let's assume you were writing a network stack. You receive an Ethernet packet to be processed. You successively pass that data up the stack from the "raw" Ethernet driver to the IP driver to the TCP driver to, say, the HTTP driver to something that processes the HTML it contains.
If you're making a new copy of the contents for each of those, you end up making at least four copies of the data before you actually get around to rendering it at all.
Using pointers can avoid a lot of that -- instead of copying the data itself, you just pass around a pointer to the data. Each successive layer of the network stack looks at its own header, and passes a pointer to what it considers the "payload" up to the next higher layer in the stack. That next layer looks at its own header, modifies the pointer to show what it considers the payload, and passes it on up the stack. Instead of four copies of the data, all four layers work with one copy of the real data.
A big use for pointers is dynamic sizing of arrays. When you don't know the size of the array at compile time, you will need to allocate it at run-time.
int *array = new int[dynamicSize];
If your solution to this problem is to use std::vector from the STL, they use dynamic memory allocation behind the scenes.
There are several scenarios where pointers are required:
If you are using Abstract Base Classes with virtual methods. You can hold a std::vector and loop through all these objects and call a virtual method. This REQUIRES pointers.
You can pass a pointer to a buffer to a method reading from a file etc.
You need a lot of memory allocated on the heap.
It's a good thing to care about memory problems right from the start. So if you start using pointers, you might as well take a look at smart pointers, like boost's shared_ptr for example.
What are good scenarios where using pointers is a must?
Interviews. Implement strcpy.
What do they allow you to do that you couldn't do otherwise?
Use of inheritance hierarchy. Data structures like Binary trees.
In which way to they make your programs more efficient?
They give more control to the programmer, for creating and deleting resources at run time.
And what about pointers to pointers???
A frequently asked interview question. How will you create two dimensional array on heap.
A pointer has a special value, NULL, that reference's won't. I use pointers wherever NULL is a valid and useful value.
I just want to say that i rarely use pointers. I use references and stl objects (deque, list, map, etc).
A good idea is when you need to return an object where the calling function should free or when you dont want to return by value.
List<char*>* fileToList(char*filename) { //dont want to pass list by value
ClassName* DataToMyClass(DbConnectionOrSomeType& data) {
//alternatively you can do the below which doesnt require pointers
void DataToMyClass(DbConnectionOrSomeType& data, ClassName& myClass) {
Thats pretty much the only situation i use but i am not thinking that hard. Also if i want a function to modify a variable and cant use the return value (say i need more then one)
bool SetToFiveIfPositive(int**v) {
You can use them for linked lists, trees, etc.
They're very important data structures.
In general, pointers are useful as they can hold the address of a chunk of memory. They are especially useful in some low level drivers where they are efficiently used to operate on a piece of memory byte by byte. They are most powerful invention that C++ inherits from C.
As to pointer to pointer, here is a "hello-world" example showing you how to use it.
#include <iostream>
void main()
{
int i = 1;
int j = 2;
int *pInt = &i; // "pInt" points to "i"
std::cout<<*pInt<<std::endl; // prints: 1
*pInt = 6; // modify i, i = 6
std::cout<<i<<std::endl; // prints: 6
int **ppInt = &pInt; // "ppInt" points to "pInt"
std::cout<<**ppInt<<std::endl; // prints: 6
**ppInt = 8; // modify i, i = 8
std::cout<<i<<std::endl; // prints: 8
*ppInt = &j; // now pInt points to j
*pInt = 10; // modify j, j = 10
std::cout<<j<<std::endl; // prints: 10
}
As we see, "pInt" is a pointer to integer which points to "i" at the beginning. With it, you can modify "i". "ppInt" is a pointer to pointer which points to "pInt". With it, you can modify "pInt" which happens to be an address. As a result, "*ppInt = &j" makes "pInt" points to "j" now. So we have all the results above.

C++: Vector of objects vs. vector of pointers to new objects?

I am seeking to improve my C++ skills by writing a sample software renderer. It takes objects consisting of points in a 3d space and maps them to a 2d viewport and draws circles of varying size for each point in view. Which is better:
class World{
vector<ObjectBaseClass> object_list;
public:
void generate(){
object_list.clear();
object_list.push_back(DerivedClass1());
object_list.push_back(DerivedClass2());
or...
class World{
vector<ObjectBaseClass*> object_list;
public:
void generate(){
object_list.clear();
object_list.push_back(new DerivedClass1());
object_list.push_back(new DerivedClass2());
?? Would be using pointers in the 2nd example to create new objects defeat the point of using vectors, because vectors automatically call the DerivedClass destructors in the first example but not in the 2nd? Are pointers to new objects necessary when using vectors because they handle memory management themselves as long as you use their access methods? Now let's say I have another method in world:
void drawfrom(Viewport& view){
for (unsigned int i=0;i<object_list.size();++i){
object_list.at(i).draw(view);
}
}
When called this will run the draw method for every object in the world list. Let's say I want derived classes to be able to have their own versions of draw(). Would the list need to be of pointers then in order to use the method selector (->) ?
Since you are explicitly stating you want to improve your C++, I am going to recommend you start using Boost. This can help you with your problem in three different ways:
Using a shared_ptr
Using a shared_ptr could declare your vector like this:
std::vector< boost::shared_ptr< ObjectBase > > object_list;
And use it like this:
typedef std::vector< boost::shared_ptr< ObjectBase > >::iterator ObjectIterator;
for ( ObjectIterator it = object_list.begin(); it != object_list.end(); it++ )
(*it)->draw(view);
This would give you polymorphism and would be used just like it was a normal vector of pointers, but the shared_ptr would do the memory-management for you, destroying the object when the last shared_ptr referencing it is destroyed.
Note about C++11: In C++11 shared_ptr became part of the standard as std::shared_ptr, so Boost is no longer required for this approach. However, unless you really need shared ownership, it is recommended you use std::unique_ptr, which was newly introduced in C++11.
Using a ptr_vector
Using a ptr_vector you would do it like this:
boost::ptr_vector< ObjectBase > object_list;
And use it like this:
typedef boost::ptr_vector< ObjectBase >::iterator ObjectIterator;
for ( ObjectIterator it = object_list.begin(); it != object_list.end(); it++ )
(*it)->draw(view);
This would again be used like a normal vector of pointers, but this time the ptr_vector manages the lifetime of your objects. The difference to the first approach is, that here your objects get destroyed when the vector gets destroyed, whereas above they may live longer than the container, if other shared_ptrs referencing them exist.
Using a reference_wrapper
Using a reference_wrapper you would declare it like this:
std::vector< boost::reference_wrapper< ObjectBase > > object_list;
And then use it like this:
typedef std::vector< boost::reference_wrapper< ObjectBase > >::iterator
ObjectIterator;
for ( ObjectIterator it = object_list.begin(); it != object_list.end(); it++ )
it->draw(view);
Notice that you do not have to dereference the iterator first as in the above approaches. This does however only work if the lifetime of your objects is managed elsewhere and is guaranteed to be longer than that of the vector.
Note about C++11: reference_wrapper has also been standardized in C++11 and is now usable as std::reference_wrapper without Boost.
As pointed out in Maciej Hs answer, your first approach results in object slicing. In general you may want to look into iterators when using containers.
You wont get what You want with this code
class World{
vector<ObjectBaseClass> object_list;
public:
void generate(){
object_list.clear();
object_list.push_back(DerivedClass1());
object_list.push_back(DerivedClass2());
What is going to happen is called object slicing. You will get a vector of ObjectBaseClass.
To make polymorphism work You have to use some kind of pointers. There are probably some smart pointers or references in boost or other libraries that can be used and make the code much safer than the second proposed solution.
As for your first question, it is generally preferred to use automatically allocated objects rather than dynamically allocated objects (in other words, not to store pointers) so long as for the type in question, copy-construction and assignment is possible and not prohibitively expensive.
If the objects can't be copied or assigned, then you can't put them directly into a std::vector anyway, and so the question is moot. If the copying and/or assignment operations are expensive (e.g. the object stores a large amount of data), then you might want to store pointers for efficiency reasons. Otherwise, it is generally better not to store pointers for exactly the reason that you mentioned (automatic deallocation)
As for your second question, yes, that is another valid reason to store pointers. Dynamic dispatch (virtual method calls) work only on pointers and references (and you can't store references in a std::vector). If you need to store objects of multiple polymorphic types in the same vector, you must store pointers in order to avoid slicing.
Well, it depends on what you are trying to do with your vector.
If you don't use pointers, then it is a copy of the object you pass in that gets put on the vector. If it is a simple object, and/or you don't want to bother with keeping track of the storage for them, this may be exactly what you want. If it is something complex, or very time-consuming to construct and destruct, you might prefer to do that work only once each and pass pointers into the vector.