I hope someone can help me how to deal with this situation. Here the issue. I have a shared library (.so, .dll, .dynlib). Within that library there is some sort of factory class that creates objects. For example my method looked like this:
class RenderSystem {
public:
int createTexture(Texture** texture, ...);
....
}
The createTexture
method in the RenderSystem
class looks like this:
int createTexture(Texture** texture, ...) {
....
*texture = new ...
return someErrorCode;
}
It was creating the Texture
instance and passing the pointer to the texture
parameter. We know that the instances created within a shared library has to be destroyed in the same. So I had methods that was deleting/destroying those textures.
I like to use shared_ptr
for all this but I have to keep the return value as integer. What is the correct way return a std::shared_ptr<Texture>
without changing the return type of the method. Is it safe to pass a reference to a std::shared_ptr<Texture>
or do I have to change the return value of the method into std::shared_ptr<Texutre>
? So is it OK to do this:
int createTexture(std::shared_ptr<Texture>& texture, ...) {
....
texture = std::shared_ptr<....>(...) or std::make_shared<...>(..);
return someErrorCode;
}
Hope I could describe the problem.
Is it safe to pass a reference...?
Yes, it is not uncommon to use the technique you describe, it is often known as return by reference (or call-by-reference ).
With some systems and conventions, the return by reference arguments are at the end of the method signature - but this is a preference and makes little difference.
... or do I have to change the return value of the method...?
Alternatives that require a change in the return type are:
Expanding the return type to be a std::tuple
or std::pair
of some sort.
Possibly the best would be to return the std::shared_ptr
and throw an exception on the error condition.
The alternatives would require a change in the return type, this is not exactly what you asked for, but alternatives worth mentioning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.