Junior — Senior
Incorrect initialization in SharedPtr constructor: what are the consequences
livecode
Task condition
What will happen if the code below is executed? You need to analyze the implementation of the constructor SharedPtr(T* p): whether it correctly initializes the internal pointer and what happens to the passed pointer p.
int* raw = new int;
std::shared_ptr<int> sp(raw);
template <class T>
class SharedPtr {
int* counterPtr = nullptr;
T* dataPtr = nullptr;
public:
SharedPtr() = default;
SharedPtr(const SharedPtr& other) {
dataPtr = other.dataPtr;
counterPtr = other.counterPtr;
(*counterPtr)++;
}
SharedPtr(T* rawPtr) {
counterPtr = new int(0);
dataPtr = new T; // problem here
}
};