Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SmartPointers with operator '++'

How can I change the code below to have unique_ptr instead of the traditional pointer?

// vector::data
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);

  int* p = myvector.data();

  *p = 10;
  ++p;
  *p = 20;
  p[2] = 100;

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

I tried the code below, but I am having E0349 no operator "++" matches these operands

  unique_ptr<int> p {myvector.data()};

  *p = 10;
  ++p; // <<< ERROR HERE >>>
  
like image 571
JRbarros Avatar asked Mar 02 '26 18:03

JRbarros


1 Answers

Smart pointers are not meant to manage individual elements of bulk data. The intent purpose of smart pointers is to manage the allocation and lifetime of complex objects.

Container objects like std::vector have iterators for the express purpose to wrap access to their bulk data internal elements without exposing a naked pointer. Use those!

like image 124
datenwolf Avatar answered Mar 05 '26 08:03

datenwolf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!