开发者

Passing temporaries as LValues

开发者 https://www.devze.com 2023-01-06 00:14 出处:网络
I\'d like to use the following idiom, that I think is non-standard. I have functions which return vectors taking advantage of Return Value Optimization:

I'd like to use the following idiom, that I think is non-standard. I have functions which return vectors taking advantage of Return Value Optimization:

vector<T> some_func()
{
    ...
    return vector<T>( /* something */ );
}

Then, I would like to use

vector<T>& some_reference;
std::swap(some_reference, some_func());

but some_func doesn't return a LValue. The above code makes sense, and I found this idiom very useful. However, it is non-standard. VC8 only emits a warning at the highest warning level, but I suspect other compilers may reject it.

My question is: Is there some way to achieve the very same thing I want to do (ie. construct a vector, assign to another, and destroy the old one) which is compliant (and does not u开发者_C百科se the assignment operator, see below) ?

For classes I write, I usually implement assignment as

class T
{
    T(T const&);
    void swap(T&);
    T& operator=(T x) { this->swap(x); return *this; }
};

which takes advantage of copy elision, and solves my problem. For standard types however, I really would like to use swap since I don't want an useless copy of the temporary.

And since I must use VC8 and produce standard C++, I don't want to hear about C++0x and its rvalue references.

EDIT: Finally, I came up with

typedef <typename T>
void assign(T &x, T y)
{
    std::swap(x, y);
}

when I use lvalues, since the compiler is free to optimize the call to the copy constructor if y is temporary, and go with std::swap when I have lvalues. All the classes I use are "required" to implement a non-stupid version of std::swap.


Since std::vector is a class type and member functions can be called on rvalues:

some_func().swap(some_reference);


If you don't want useless copies of temporaries, don't return by value. Use (shared) pointers, pass function arguments by reference to be filled in, insert iterators, ....

Is there a specific reason why you want to return by value?


The only way I know - within the constraints of the standard - to achieve what you want are to apply the expression templates metaprogramming technique: http://en.wikipedia.org/wiki/Expression_templates Which might or not be easy in your case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号