Random Efficacy Question

Which is the better? Or are they both basically equal?

1
2
3
4
5
std::string myFunc() {
   std::string myStr;
   //do stuff it
   return myStr;
}


1
2
3
4
5
std::stringstream myFunc() {
   std::stringstream myStream;
   //do stuff it
   return myStream;
}
closed account (S6k9GNh0)
I'm thinking stringstream. But tbh, one can't substitute the other so why does it matter?
Hello firedraco,

The difference is in a loaded meaning while in there.
Both of them should be freed after all.
It is just for your convinience here.
Is the second even possible? Streams don't have copy constructor
closed account (S6k9GNh0)
@ EverBeginner: That doesn't make sense.

@ Bazzy: Where is the stringstream copy constructor used?
Where is the stringstream copy constructor used?


right here: return myStream;

The local myStream is destroyed because it loses scope, and so a copy of it is returned.
It's true. std::stringstream's copy constructor is private, like all streams' copy constructors.
Ah, that would explain the errors "Cannot access private member in sstream"...thanks all.
closed account (S6k9GNh0)
Can't you return a reference to the stream? As long as you have a way it doesn't get destroyed after scope.

EDIT: This is done on a lot of stream based functions is it returns the stream through a reference or pointer.
Last edited on
As long as you have a way it doesn't get destroyed after scope.
LOL, yes it does. Allocators aren't magical. They can't count language references, only references in the objects they are aware of. All objects created in the stack are destructed when their frame expires (i.e. when the control flow moves out of the block they were created in).

It is possible, however, to return a pointer to dynamically allocated stream.
Last edited on
closed account (S6k9GNh0)
I have no clue what you just said helios....

1
2
3
4
5
std::stringstream& myFunction()
{
      std::stringstream *myStream = new std::stringstream;
      return *myStream;
}


This is what I mean. You can allocate memory dynamically and then send a pointer or reference as a return statement. How is this magical?
Last edited on
What you did = (as helios said was possible) returning a pointer to dynamically allocated stream.
I have no clue what you just said helios.... [...] This is what I mean. You can allocate memory dynamically and then send a pointer or reference as a return statement. How is this magical?
Can't you return a reference to the stream?

You're kinda mixing things up, there. First, it's obviously not the same to return a pointer or a reference; second, you can't return a reference to a dynamic object.
Last edited on
Topic archived. No new replies allowed.