Итак, мой вопрос заключается в следующем: не было ли попыток добавить в современный C++ «слабый указатель», который не зависит от использования общих указателей? Я имею в виду просто указатель, который становится NULL при удалении в любой части программы. Есть ли причина не использовать такую самодельную обертку?
Чтобы лучше объяснить, что я имею в виду, ниже приведен такой «слабый указатель», который я сделал. Я назвал его WatchedPtr.
Код: Выделить всё
#include
#include
template
class WatchedPtr {
public:
// the only way to allocate new pointer
template
WatchedPtr(ARGS... args) : _ptr (new T(args...)), _allocated (std::make_shared(true)) {}
WatchedPtr(const WatchedPtr& other) : _ptr (other._ptr), _allocated (other._allocated) {}
// delete the pointer
void del () {delete _ptr; *_allocated = false;}
auto& operator=(const WatchedPtr &other) { return *this = other; }
bool isNull() const { return *_allocated; }
T* operator->() const { return _ptr; }
T& operator*() const { return *_ptr; }
private:
T* _ptr;
std::shared_ptr _allocated;
};
struct S {
int a = 1;
};
int main () {
WatchedPtr p1;
WatchedPtr p2(p1);
p1->a = 8;
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/55500183/why-is-there-no-weak-pointer-for-raw-pointer-or-is-there[/url]
Мобильная версия