I am writing a vector class that takes ownership of member pointers. As far as possible, I want to reuse std:vector. I have been trying private and public inheritance; in both cases I am running into difficulties.
For private inheritance, see issue how to write forward iterator using private std::vector base class.
For public inheritance, I need to delete certain methods from the base class. Specifically, I need to prevent users from replacing member pointers without deleting objects. So I want to delete T* & operator[](int i)
. At the same time, I still want to support T* const operator[](int i) const
. Somehow, the deletion of the former seems to overrule the reimplementation of the latter. Here a minimal complete example:
#include <vector>
#include <iostream>
/* Vector class that takes ownership of member pointers */
template <class T>
class OwningVector : public std::vector<T*> {
using super = std::vector<T*>;
public:
~OwningVector() { /* deletes objects pointed to */ };
T* & operator[](int i) = delete;
T* const operator[](int i) const { return super::operator[](i); }
};
class A {
public:
A(int m) : m(m) {}
int m;
};
int main() {
OwningVector<A> v;
v.emplace_back(new A(1));
std::cout << v[0]->m << std::endl;
}
Compilation fails:
hh.cpp: In function ‘int main()’:
hh.cpp:23:21: error: use of deleted function ‘T*& OwningVector<T>::operator[](int) [with T = A]’
23 | std::cout << v[0]->m << std::endl;
| ^
hh.cpp:9:10: note: declared here
9 | T* & operator[](int i) = delete;
| ^~~~~~~~
CodePudding user response:
You are trying to re-invent the wheel. All you need is a vector of smart pointers:
template <class T>
using OwningVector = std::vector<std::unique_ptr<T>>;
CodePudding user response:
From the comments:
Using v[0]->m
will call the const-version of the operator if v
is const. Otherwise it calls the non-const operator.
The fact that you don't write to v
doesn't affect this.