I have some class which manages some resources. You get get a reference to one of those resources from this managing class. Resources are heavy-weight objects, so you normally don't want to copy them. In my case, a base-class for resources is no solution, because my 'resource-manager' is a template class which should work with already defined resource classes of other people. I made some simple example to show my problem:
#include <iostream>
// copyable class
class Copyable {
public:
Copyable() = default;
Copyable(const Copyable&) {
std::cout << "Copyconstructor called" << std::endl;
}
Copyable& operator=(const Copyable&) {
std::cout << "assignment operator called" << std::endl;
return *this;
}
};
// non copyable class
class NonCopyable {
public:
NonCopyable() = default;
private:
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
};
// some class that can return a reference
template <typename T>
class SomeHolder {
private:
T some_member;
public:
T& getReference() {
return some_member;
}
};
int main() {
SomeHolder<Copyable> holder_1;
auto copyable_1 = holder_1.getReference();
auto ©able_2 = holder_1.getReference();
SomeHolder<NonCopyable> holder_2;
//auto noncopyable_1 = holder_2.getReference();
auto &noncopyable_2 = holder_2.getReference();
}
The class SomeHolder returns a reference on the owned object. As you see in line 39, this reference gets copied. Normal way to get the reference is done in line 40. But if you miss the & you get a copy, which you normally don't want. If you uncomment line 39, you get an error because the resource isn't copyable in this case. Like i said before, wanting all resources to be not copyable isn't a solution in my case. Do you have ideas to other design decisions? I write this class to hold resources for games. I am writing a small library for recurring tasks. So i don't know if your framework works with copyable textures and sounds. Maybe there is no great solution for my problem, but if you have design suggestions, let me know.
Aucun commentaire:
Enregistrer un commentaire