Boost logo

Boost :

From: mfdylan (dylan_at_[hidden])
Date: 2002-02-04 21:45:13


--- In boost_at_y..., "Rainer Deyke" <root_at_r...> wrote:
>
> std::vector<int> g()
> {
> std::vector<int> first, second;
> // Do various operations on 'first' and 'second' here.
> return (first.size() > second.size()) ? first : second;
> }
>
> std::vector<int> v(g());
>
I would love to see a compiler that could compile that into efficient
code. In theory of course it can - the semantics of std::vector are
part of the language, so it should essential be able to reduce the
above to only 2 memory allocations and one free.
But if you wanted to be able to write your own classes that the
compiler could generate similarly efficient code you essentially need
a way of knowing in what is currently the "copy" constructor that the
parameter being passed is going out of scope, so you can safely steal
its resources. I'm pretty sure this can only be done with language
help. One possibility I guess is an extra type-qualification, call
it, um "expiring":

vector(expiring vector& other)
{
 swap(other);
}

But looking at the implementation, why not just have the compiler
call swap directly? That is, if your class implements a "swap"
member, and you are constructing or assigning from an 'expiring'
object, the swap() call is used instead of the copy
constructor/assignment operator. Giving a named member special
status is perhaps a little anathema to the existing standard
("operator=" almost fits this description), and I believe Java does
this sort of thing for "to_string" etc. I'm not sure if the same
should be done for a "swap" global, especially if it isn't compilable
for that type.

Anyway just a thought (shouldn't this discussion be in c.l.c++.m or
even comp.std.c++?)

Dylan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk