I stumbled upon some odd behaviour in my c++ program.
I have a class which should wrap a unique resource. This resource has to acquired before its use and released afterwards.
My Wrapper gets the acquired resource and should release the resource when it is destroyed.
I have also implemented custom copy-, move constructor and assignment operator to to move the resource to the next wrapper and invalidate the original one, so that I am able to forward the held resource.
Now to the problem, I implemented a custom ostream print operator like: friend std::ostream& operator<<(std::ostream& os, const Wrapper& wrapper)
for some debug messages.
However when this operator gets called, my program also calls the copy constructor of my Wrapper class and therefore effectively moves the acquired resource into the print function, witch will be released, because the local wrapper goes out of scope.
To my understanding the const Wrapper&
parameter should only be a reference and therefore neither the copy nor the move constructor should be called. And also the local wrapper object should not be destructed, because there should not be a local wrapper object in the first place.
Has someone an idea why this is happening?
Here is a minimal example of the wrapper class:
class Wrapper{
private:
mutable ResourceType* resource;
Wrapper(ResourceType* resource):
resource(resource){
}
public:
Wrapper():
resource(nullptr)
{
}
Wrapper(const Wrapper& other):
resource(other.resource){
other.resource = nullptr;
}
Wrapper(Wrapper&& other):
resource(other.resource){
other.resource = nullptr;
}
~Wrapper(){
if(resource){
// Release resource
}
}
void operator= (const Wrapper& other){
resource = other.resource;
other.resource = nullptr;
}
void operator= (Wrapper&& other){
resource = other.resource;
other.resource = nullptr;
}
friend std::ostream& operator<<(std::ostream& os, const Wrapper& wrapper){
os << "Wrapper for " << wrapper.resource;
return os;
}
}
I already tried to read up upon pass by reference, but I only found that no new object should be created by a reference parameter.
Rainova is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.