Reputation: 2418
I read that using raw pointers in C++ is bad. Instead we should use auto_ptr
. In the below code I am populating a vector in foo()
that is created in the main()
. Am I doing it right or is there a better way to do without using explicit pointers.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string> *v){
(*v).push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(&v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
Upvotes: 3
Views: 2706
Reputation: 455
You can begin to think about using auto_ptr when you deal with objects created on heap (e.g. a class instance created by "new"). Your vector holds its elements by value, std::string elements it is. So you don't need to consider auto_ptr here at all. If your vector would hold instances created on heap then you could use something like this:
std::vector< auto_ptr< MyType > > vec;
auto_ptr< MyType > a( new MyType() );
vec.push_back( a );
and then when your vector elements get erased by e.g. your vec leaving its scope then instance 'a' will get deleted automatically.
With other words, auto_ptr is a kind of garbage collector which does a kind of automatic object deletion for you. See here for more information about auto_ptr http://www.cplusplus.com/reference/std/memory/auto_ptr
Upvotes: 0
Reputation: 726549
C++ uses references for what you are trying to do:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string>& v){
v.push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
References and pointers are similar, with one very important distinction: there is no such thing as a null reference (Constructing one is Undefined Behavior in C++ you can construct one, but doing so is considered a hack).
Upvotes: 4
Reputation: 62439
In C++ you can avoid the pointer and use a pass-by-reference:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string>& v){
v.push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
Upvotes: 3