c++ - Correct way to claim ownership of existing raw pointer -
i have code claims ownership of sequence of raw pointers, , wondering if there acceptable way this? i'm looking way enforce ownership in code greater degree. mainly, i've been wondering whether or not constructor should taking vector of unique pointers directly.
as sidenote, once ownership has been claimed, data supposed immutable.
the code follows pattern of class x below.
#include <iostream> #include <memory> #include <vector> using namespace std; // readability purposes class x { public: const vector< unique_ptr<const int> > data; // in case private // constructor: x object take ownership of data // destroying when going out of scope x (vector<int*> rawdata) : data { make_move_iterator(rawdata.begin()), make_move_iterator(rawdata.end()) } { } }; int main() { // illustrating issues claiming ownership of existing pointers: vector<int*> rawdata { new int(9) , new int(4) }; int* rawpointer = rawdata[0]; { // new scope x x(rawdata); cout << *(x.data[0]) << endl; // unique pointer points 9 *rawpointer = 7; cout << *(x.data[0]) << endl; // unique pointer points 7 } cout << *rawpointer << endl; // pointer has been deleted, prints garbage return 0; }
it difficult post answer without detailed knowledge of situation. recommendation attach data unique_ptr known. can move unique_ptr , out of vectors @ will. example:
#include <iostream> #include <memory> #include <vector> using namespace std; // readability purposes class x { public: const vector< unique_ptr<const int> > data; // in case private // constructor: x object take ownership of data // destroying when going out of scope x (vector<unique_ptr<const int>>&& v) : data { std::move(v) } { } }; vector<unique_ptr<const int>> collectrawdata() { auto rawdata = {9, 4}; vector<unique_ptr<const int>> data; (auto const& x : rawdata) data.push_back(make_unique<int>(x)); return data; } int main() { auto rawdata = collectrawdata(); { // new scope x x(std::move(rawdata)); cout << *(x.data[0]) << endl; // unique pointer points 9 cout << *(x.data[1]) << endl; // unique pointer points 4 } }
Comments
Post a Comment