The difference between smart pointers and raw pointers has been discussed before (e.g. When should I use raw pointers over smart pointers?), but I can't quite get the answer to this question from the material I have been reading the last day or so.
I have a class A
that has a pointer int* a
to some data. In the context I am thinking about, the value that a
points to might be used somewhere else in the program so A
does not have ownership over a
, it just refers to it. For example, a house exists (e.g. int h
) and a person (i.e. class) has a reference to their house (e.g. int* my_h
).
The first way I handled this was without using smart pointers, but I am curious about the benefits of using smart pointers in this example. I suspect there are not many because ownership really isn't much of an issue and I am not calling new
and delete
.
The example with raw pointers:
#include<iostream>
class A{
public:
A(int a_val){
std::cout << "Creating A instance ";
a = &a_val;
std::cout << "with a = " << *a << std::endl;
};
private:
int* a;
};
int main()
{
int x = 5;
std::cout << "x is " << x << std::endl;
A a(x);
return 0;
}
Here, a
has the raw pointer int* a
, which is assigned to &x
in main()
.
The example with smart pointers (a unique_ptr
):
#include<memory>
#include<iostream>
class A{
public:
A(std::unique_ptr<int> a_val){
std::cout << "Creating A instance ";
a = std::move(a_val);
std::cout << "with a = " << *a << std::endl;
};
private:
std::unique_ptr<int> a;
};
int main()
{
std::unique_ptr<int> x = std::make_unique<int> (5);//int x = 5;
std::cout << "x is " << *x << std::endl;
A a(std::move(x));
return 0;
}
The use of unique_ptr
seems overkill here to me, and doesn't benefit readability or performance. Is that correct?
EDIT
As pointed out (...) in the comments, there were a number of problems with the original example. The raw pointer example should be:
#include<iostream>
class A{
public:
A(int* a_val){
std::cout << "Creating A instance ";
a = a_val;
std::cout << "with a = " << *a << std::endl;
};
private:
int* a;
};
int main()
{
int x = 5;
std::cout << "x is " << x << std::endl;
A a(&x);
return 0;
}
and the smart pointer example should perhaps use a shared_ptr
.
To be more specific, I am interested in cases where this scales up to large numbers of instances of classes, which have pointers (or vectors of pointers) to data structures defined elsewhere. For instance, in agent based models, agents sometimes need to 'find' another agent, and thus a vector of pointers could (in my understanding) be used to refer to which other agents one particular agents should 'know about'. The agents themselves will be created outside of the agent class.