Smart Pointers
May 19, 2013 at 9:44pm UTC
When i try to compile this code it gives me a error during run-time saying "*program name* has stopped working"
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;
int main()
{
unique_ptr<double > ptr2;
double a=30;
*ptr2 = a;
return 0;
}
Why is this happening?
Also why do you need the asterisk on smart pointers to assign them a value? Is it just because, or is there a reason.
Last edited on May 19, 2013 at 9:45pm UTC
May 19, 2013 at 9:55pm UTC
Because you're dereferencing a pointer that hasn't been made to point at a valid memory location.
1 2 3 4 5 6 7 8
int main()
{
double * ptr2 = nullptr ;
double a ;
*ptr2 = a ;
delete ptr2 ;
return 0 ;
}
is essentially the same code with a normal pointer.
May 19, 2013 at 10:03pm UTC
Oh I got it, I got confused with some code in my book:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;
unique_ptr<double > treble(double );
int main(void )
{
double num(5.0);
unique_ptr<double > ptr(nullptr );
ptr = treble(num);
cout << endl << "Three times num = " << 3.0*num;
cout << endl << "Result = " << *ptr;
cout << endl;
return 0;
}
unique_ptr<double > treble(double data)
{
unique_ptr<double > result(new double (0.0));
*result = 3.0*data;
return result;
}
This part:
1 2 3 4 5
unique_ptr<double > treble(double data)
{
unique_ptr<double > result(new double (0.0));
*result = 3.0*data;
return result;
Notice how it does *result and assigns the value of result to 3.0*data?
I thought it was being assigned a rvalue because smart pointers support that and I thought you needed the asterisk for smart pointers.
Well thanks again cire, you always point out my stupid mistakes.
May 19, 2013 at 10:29pm UTC
Wait can Smart pointers only point to dynamically created objects and not normal objects?
May 19, 2013 at 11:44pm UTC
Seen as the purpose of smart pointers is to automatically delete the memory they "own" once it's no longer needed (or an exception wreaked havoc), I'd say they shouldn't "point" to normal object or they'll try to delete it too.
I think. I may be completely wrong.
http://ideone.com/m1zAkO
May 20, 2013 at 12:53am UTC
Oh ok thanks, that makes sense. So they can only point to dynamically allocated objects, thanks!
Topic archived. No new replies allowed.