|
![](/i/fill.gif) |
>> Is that about right?
>
> That's the whole idea in C++ class design. If you write a class which is
> not safe to use like that, then your design is bad.
>
> C++ classes have been designed to allow you to do that. As long as
> you just create local instances of them and pass them by value (in other
> words, as long as you don't use the keyword 'new' nor store pointers which
> last longer than the object), if the class has been implemented properly
> it's completely safe. (Ok, there are some exceptions, but basically.)
That's certainly a big step up from C, where as soon as you touch
something that's dynamically allocated, basically your program is almost
guaranteed to segfault. But then, C doesn't provide any way for a
library designer to control what happens with their stuff at the
caller's end. That's very machine efficient, but not terribly safe...
> The nice thing about this is that whether copying the vector object
> causes a deep-copy of the array, whether it's reference-counted, or
> whether it uses copy-on-write, the interface doesn't change in any way.
> In other words, the internal implementation is completely transparent and
> its usage is exactly the same regardless.
That's a good property.
>> Here's another question: Suppose you have a function that's supposed to
>> create a new vector and return it to the caller. What's the best way to
>> do that?
>
> One common idiom is for the function to take the vector as reference:
>
> void createVector(whatever, std::vector<int>& result) { ... }
>
> and then you give your vector as parameter, and the function will then
> add the data to it.
That seems like the simplest thing to do then. The allocation and
lifetime of the object is quite obvious by looking at the caller, and
it's simple to implement at the called end.
Post a reply to this message
|
![](/i/fill.gif) |