Reputation: 31
I am new to C++ and am trying to do a very basic implementation of a shared_ptr (WIP). I am trying to delete a heap-allocated pointer in the destructor right after finding the underlying value by dereferencing. While the dereferencing happens fine, deletion of '''ref_count''' variable is causing problems. Can someone please help? '''
#include<iostream>
template<typename T>
class shared_ptr{
private:
T* native_ptr_ = nullptr;
int* ref_count_ = nullptr;
inline void increment_count() {
*ref_count_++;
}
inline void decrement_count() {
*ref_count_--;
}
public:
shared_ptr() {
std::cout << "shared_ptr: empty constructor" << std::endl;
native_ptr_ = nullptr;
ref_count_ = nullptr;
}
shared_ptr(T* ptr) {
std::cout << "shared_ptr: constructor" << std::endl;
if (ptr) {
native_ptr_ = ptr;
ref_count_ = new int(1);
}
}
~shared_ptr() {
std::cout << "shared_ptr: destructor" << std::endl;
if (ref_count_) {
decrement_count();
if (ref_count_ && use_count() == 0) {
std::cout << *ref_count_ << " " << *native_ptr_ << std::endl;
delete ref_count_;
delete native_ptr_;
ref_count_ = nullptr;
native_ptr_ = nullptr;
}
}
}
int use_count() const {
if(ref_count_) {
return *ref_count_;
} else {
return 0;
}
}
};
int main() {
// case1
int* temp = new int(0);
shared_ptr<int> a1(temp);
return 0;
}
'''
'''
shared_ptr: constructor
shared_ptr: destructor
0 0
free(): invalid pointer
Aborted (core dumped)
'''
Upvotes: 0
Views: 536
Reputation: 7863
Operator precedence is causing you problems. You're actually decrementing the pointer, then deferencing the new address. If you crank up your warnings, you'll get something like this:
p.cpp:35:7: required from ‘shared_ptr<T>::~shared_ptr() [with T = int]’
p.cpp:58:26: required from here
p.cpp:14:5: warning: value computed is not used [-Wunused-value]
14 | *ref_count_--;
| ^
You can add parenthesis to de-reference the pointer before decrementing.
Upvotes: 6