How to self-document a function that use a custom allocator - to remind that its user must not cache the returned result.
I have a library and a user class, they use in-house polymorphic allocator.
- Library : uses one-frame-allocator to generate return result of
Library:fLib
.
The returned result will be invalid at the end of time-step. - User : want to cache the return result of
Library:fLib
to use in later frame.
It is a bad design ; hence it needs some warning.
Here is the snippet. (full demo).
class Library{
public:
OneFrameAllocator allo_;
public: Report fLib(){ //<-- may need some semantic documentation
Report report;
report.setAllocator(&allo_);
return report;
}
};
Library lib;
class User{
Report tmpCache;
public: void fUser(){
Report arr=lib.fLib(); //<-- still OK (should not warn)
tmpCache=arr; //<-- wrong usage, but hard to detect
}
};
int main(){
User user;
user.fUser();
lib.allo_.clearOneFrame();
//HERE: user.tmpCache become dangling pointer internally (danger)
return 0;
}
Question
How to warn coder of User
not to cache return result of Library::fLib()
semantically
(i.e. more than just comment /**/
)?
I am considering to use smart pointer, but I don't think it can help because memory become invalidated from custom allocator, not from deleting a unique_ptr
.
In real life, Library
can also be a custom Array
(that acts similar as std::vector
).
In such case, the danger less obvious - "User
try to copy Array
" doesn't seem to be dangerous.
Sorry if the question is too newbie, I am very new to custom allocators.
Edit:
After looking into the rule of three. (thank paddy)
I believe the core of my problem can be depicted as :-
(pseudo code)
class Lib{
OneFrameAllocator allo;
public: std::unique_ptr<int> make_unique(){
return allo.make_unique<int>();
//^ memory will be invalidated when call "allo.clearOneFrame()"
}
public: void update(){
allo.clearOneFrame();
}
};
Library lib;
class User{
std::unique_ptr<int> cache=nullptr;
public: void fUser(){
//do something about "cache" <--- crash expected at 2nd frame
std::unique_ptr<int> temp=lib.make_unique(); //<-- still OK
cache=std::move(temp); //<-- danger
}
};
int main(){
User user;
//--- 1st frame ----
user.fUser();
lib.update();
//--- 2nd frame ----
user.fUser(); //<--- crash expected
lib.update();
}
I believe the problem is :
The class that has ownership (User
) is not the class that controls memory allocation (Library
).
It is not a good design, so I want to find a way to warn the coder of User
that something is wrong by using C++ syntax/semantic-clue.