Followers 0

# Are pointers initialized to nullptr in a vector?

## 10 posts in this topic

class A{...};

int main()
{
std::vector<A*> vec;
vec.resize(10);
std::cout<<(vec[9]==nullptr); //prints 1
}

?

?

?

I want to make sure this happens on every system.

Are pointers initialized to nullptr?

1

##### Share on other sites
I can't remember, but if you want to be 100% sure, you can do it explicitly:
vec.resize( 10, nullptr );
1

##### Share on other sites
Also, you should try to use vectors of objects, not vectors of pointers, unless you have a good reason not to. If you really do need pointers (say, because you are storing objects of different derived classes, to obtain polymorphism), you probably want to use a vector of unique_ptr.
0

##### Share on other sites

Every element of a vector gets initialized with its default value, which is NULL for pointers.

So the basic answer is “Yes”.

L. Spiro

1

##### Share on other sites
afaik the initial value is compiler related and not defined in standard. so you can't be sure 100%, but basically most compilers do it this way.
0

##### Share on other sites
ah, ok. thanks for correction.
2

##### Share on other sites

Also, you should try to use vectors of objects, not vectors of pointers, unless you have a good reason not to. If you really do need pointers (say, because you are storing objects of different derived classes, to obtain polymorphism), you probably want to use a vector of unique_ptr.

boost::ptr_vector is here for that idiom.

0

##### Share on other sites

Also, you should try to use vectors of objects, not vectors of pointers, unless you have a good reason not to. If you really do need pointers (say, because you are storing objects of different derived classes, to obtain polymorphism), you probably want to use a vector of unique_ptr.

boost::ptr_vector is here for that idiom.

My understanding is that boost::ptr_vector<blah> doesn't have any advantages over using std::vector<std::unique_ptr<blah>> now that we have move semantics. But I would love to learn something new, so please enlighten me.
0

##### Share on other sites
About the only advantage I know of is that the pointer containers propagate constness. That is if you have a const_iterator to a ptr_vector you can't modify the stored object through that iterator, but a const_iterator to a std::vector of std::unique_ptrs can still be used to modify the pointed to objects.
0

## Create an account

Register a new account