reference - How to "return an object" in C++? -
I know that title seems familiar because there are many similar questions, but I'm asking for a different aspect of the problem (I know the difference between things on the heap and putting them on a heap).
In Java, I can always reference the reference to "local" objects
calculating public talk () {thing thing = new thing}; // calculate and modify the thing to be brought back; } In C ++, I have 2 options for doing something (1) whenever I need to "back" something Even then, I can use references
calculating zero thing (thing and thing) {// calculate and modify the thing}
Then use it like this
Talk; CalculateThing (thing);
(2) Or else I can return a pointer on a dynamically allocated object
thing * calculateThing () {Thing * thing New Thing ()); // calculate and modify the thing to be brought back; }
Then use it like this
thing * object = counting (); Delete thing;
In order to use the first approach, I do not have to free the memory manually, but it makes it difficult for me to read the code. There is a problem with the second approach, I have to remove the object;
Remember that which does not look good enough I do not want to return a copied value because it is disabled (I think), then the questions come here
- There is a third solution (whose price is not needed to copy)?
- Is there any problem if I stick to the solution first?
- When and why should I use another solution?
I do not want to return a copy value because it is disabled
Prove it.
Look at RVO and NRVO, and see C ++ 0x Move-Semantic in C ++ 03 In most cases, one out parameter is a good way to make your code ugly, and C ++ In 0x you are actually harming yourself by using one out parameter.
Just write clean code, return from the price. If performance is a problem, then profile (prevention from guess), and find out what you can do to fix it. Will not return the work from the possibility of this happening.
He said, if you have died after writing this way, then you probably want to parameter out. This avoids dynamic memory allocation, which is safe and generally fast. It is necessary that you have a way of creating an object before calling a function, which is not always understood for all the objects.
If you want to use dynamic allocation, it can be minimized, put it in a smart pointer (it should be done anyway anyway), then you have to delete anything Do not worry, things are exception-safe, etc. The only problem is that the possibility of returning from the price is slow!
Comments
Post a Comment