2

I'm studying smart pointers, in particular scoped_ptr. I read about the operators * and ->. I tried to run this code:

int main(){
  boost::scoped_ptr<int>number(new int);
  *number = 432;
  std::cout<<"Value: "<<*number <<std::endl<< " Adress: "<< number <<std::endl;
  return 0;
}

And the result is:

Value: 432 Adress: 1

That isn't correct.

How have I to use -> operator to get the correct address?

linofex
  • 340
  • 1
  • 2
  • 17
  • do you want the address of the smart pointer, or the address of the int? What you're doing right now is printing the numerical value of the smart pointer, which seems to be 1 (probably the reference count). – Marcus Müller May 28 '16 at 16:46
  • `int* p = number.operator -> ();` –  May 28 '16 at 16:48
  • 2
    There is no overload of `<<` for `scoped_ptr`. Instead, it's implicitly converted to `bool` (there is such a conversion) and `bool` prints as `0`and `1` by default. Since the pointer isn't null, it converts to `true`. – molbdnilo May 28 '16 at 16:53

1 Answers1

3

Use get() member function:

boost::scoped_ptr<int>number(new int);
*number = 432;
std::cout<<"Value: "<<*number <<std::endl<< " Adress: "<< number.get() <<std::endl;

More details here

fnc12
  • 2,241
  • 1
  • 21
  • 27
  • Thank you! On my slides there isn't the `get()` function. Good to know! – linofex May 28 '16 at 17:20
  • 1
    @linofex if you don't have `get()` function you can take address another way: `std::cout<<" Adress: "<< &*number< – fnc12 May 28 '16 at 17:23