Search Results

Search found 52 results on 3 pages for 'rvalue'.

Page 1/3 | 1 2 3  | Next Page >

  • C++0x rvalue references - lvalues-rvalue binding

    - by Doug
    This is a follow-on question to http://stackoverflow.com/questions/2748866/c0x-rvalue-references-and-temporaries In the previous question, I asked how this code should work: void f(const std::string &); //less efficient void f(std::string &&); //more efficient void g(const char * arg) { f(arg); } It seems that the move overload should probably be called because of the implicit temporary, and this happens in GCC but not MSVC (or the EDG front-end used in MSVC's Intellisense). What about this code? void f(std::string &&); //NB: No const string & overload supplied void g1(const char * arg) { f(arg); } void g2(const std::string & arg) { f(arg); } It seems that, based on the answers to my previous question that function g1 is legal (and is accepted by GCC 4.3-4.5, but not by MSVC). However, GCC and MSVC both reject g2 because of clause 13.3.3.1.4/3, which prohibits lvalues from binding to rvalue ref arguments. I understand the rationale behind this - it is explained in N2831 "Fixing a safety problem with rvalue references". I also think that GCC is probably implementing this clause as intended by the authors of that paper, because the original patch to GCC was written by one of the authors (Doug Gregor). However, I don't this is quite intuitive. To me, (a) a const string & is conceptually closer to a string && than a const char *, and (b) the compiler could create a temporary string in g2, as if it were written like this: void g2(const std::string & arg) { f(std::string(arg)); } Indeed, sometimes the copy constructor is considered to be an implicit conversion operator. Syntactically, this is suggested by the form of a copy constructor, and the standard even mentions this specifically in clause 13.3.3.1.2/4, where the copy constructor for derived-base conversions is given a higher conversion rank than other implicit conversions: A conversion of an expression of class type to the same class type is given Exact Match rank, and a conversion of an expression of class type to a base class of that type is given Conversion rank, in spite of the fact that a copy/move constructor (i.e., a user-defined conversion function) is called for those cases. (I assume this is used when passing a derived class to a function like void h(Base), which takes a base class by value.) Motivation My motivation for asking this is something like the question asked in http://stackoverflow.com/questions/2696156/how-to-reduce-redundant-code-when-adding-new-c0x-rvalue-reference-operator-over ("How to reduce redundant code when adding new c++0x rvalue reference operator overloads"). If you have a function that accepts a number of potentially-moveable arguments, and would move them if it can (e.g. a factory function/constructor: Object create_object(string, vector<string>, string) or the like), and want to move or copy each argument as appropriate, you quickly start writing a lot of code. If the argument types are movable, then one could just write one version that accepts the arguments by value, as above. But if the arguments are (legacy) non-movable-but-swappable classes a la C++03, and you can't change them, then writing rvalue reference overloads is more efficient. So if lvalues did bind to rvalues via an implicit copy, then you could write just one overload like create_object(legacy_string &&, legacy_vector<legacy_string> &&, legacy_string &&) and it would more or less work like providing all the combinations of rvalue/lvalue reference overloads - actual arguments that were lvalues would get copied and then bound to the arguments, actual arguments that were rvalues would get directly bound. Questions My questions are then: Is this a valid interpretation of the standard? It seems that it's not the conventional or intended one, at any rate. Does it make intuitive sense? Is there a problem with this idea that I"m not seeing? It seems like you could get copies being quietly created when that's not exactly expected, but that's the status quo in places in C++03 anyway. Also, it would make some overloads viable when they're currently not, but I don't see it being a problem in practice. Is this a significant enough improvement that it would be worth making e.g. an experimental patch for GCC?

    Read the article

  • C++0x rvalue references and temporaries

    - by Doug
    (I asked a variation of this question on comp.std.c++ but didn't get an answer.) Why does the call to f(arg) in this code call the const ref overload of f? void f(const std::string &); //less efficient void f(std::string &&); //more efficient void g(const char * arg) { f(arg); } My intuition says that the f(string &&) overload should be chosen, because arg needs to be converted to a temporary no matter what, and the temporary matches the rvalue reference better than the lvalue reference. This is not what happens in GCC and MSVC. In at least G++ and MSVC, any lvalue does not bind to an rvalue reference argument, even if there is an intermediate temporary created. Indeed, if the const ref overload isn't present, the compilers diagnose an error. However, writing f(arg + 0) or f(std::string(arg)) does choose the rvalue reference overload as you would expect. From my reading of the C++0x standard, it seems like the implicit conversion of a const char * to a string should be considered when considering if f(string &&) is viable, just as when passing a const lvalue ref arguments. Section 13.3 (overload resolution) doesn't differentiate between rvalue refs and const references in too many places. Also, it seems that the rule that prevents lvalues from binding to rvalue references (13.3.3.1.4/3) shouldn't apply if there's an intermediate temporary - after all, it's perfectly safe to move from the temporary. Is this: Me misreading/misunderstand the standard, where the implemented behavior is the intended behavior, and there's some good reason why my example should behave the way it does? A mistake that the compiler vendors have somehow all made? Or a mistake based on common implementation strategies? Or a mistake in e.g. GCC (where this lvalue/rvalue reference binding rule was first implemented), that was copied by other vendors? A defect in the standard, or an unintended consequence, or something that should be clarified?

    Read the article

  • non-class rvalues always have cv-unqualified types

    - by FredOverflow
    §3.10 section 9 says "non-class rvalues always have cv-unqualified types". That made me wonder... int foo() { return 5; } const int bar() { return 5; } void pass_int(int&& i) { std::cout << "rvalue\n"; } void pass_int(const int&& i) { std::cout << "const rvalue\n"; } int main() { pass_int(foo()); // prints "rvalue" pass_int(bar()); // prints "const rvalue" } According to the standard, there is no such thing as a const rvalue for non-class types, yet bar() prefers to bind to const int&&. Is this a compiler bug? EDIT: Apparently, this is also a const rvalue :)

    Read the article

  • Move from *this in an rvalue method?

    - by FredOverflow
    In C++0x, methods can be overloaded on whether or not the expression that denotes the object on which the method is called is an lvalue or an rvalue. If I return *this from a method called via an rvalue, do I need to explicitly move from *this or not? Foo Foo::method() && { return std::move(*this); // Is this move required or not? } Unfortunately, I can't simply test this on my compiler since g++ does not support this feature yet :(

    Read the article

  • Some clarification on rvalue references

    - by Dennis Zickefoose
    First: where are std::move and std::forward defined? I know what they do, but I can't find proof that any standard header is required to include them. In gcc44 sometimes std::move is available, and sometimes its not, so a definitive include directive would be useful. When implementing move semantics, the source is presumably left in an undefined state. Should this state necessarily be a valid state for the object? Obviously, you need to be able to call the object's destructor, and be able to assign to it by whatever means the class exposes. But should other operations be valid? I suppose what I'm asking is, if your class guarantees certain invariants, should you strive to enforce those invariants when the user has said they don't care about them anymore? Next: when you don't care about move semantics, are there any limitations that would cause a non-const reference to be preferred over an rvalue reference when dealing with function parameters? void function(T&); over void function(T&&); From a caller's perspective, being able to pass functions temporary values is occasionally useful, so it seems as though one should grant that option whenever it is feasible to do so. And rvalue references are themselves lvalues, so you can't inadvertently call a move-constructor instead of a copy-constructor, or something like that. I don't see a downside, but I'm sure there is one. Which brings me to my final question. You still can not bind temporaries to non-const references. But you can bind them to non-const rvalue references. And you can then pass along that reference as a non-const reference in another function. void function1(int& r) { r++; } void function2(int&& r) { function1(r); } int main() { function1(5); //bad function2(5); //good } Besides the fact that it doesn't do anything, is there anything wrong with that code? My gut says of course not, since changing rvalue references is kind of the whole point to their existence. And if the passed value is legitimately const, the compiler will catch it and yell at you. But by all appearances, this is a runaround of a mechanism that was presumably put in place for a reason, so I'd just like confirmation that I'm not doing anything foolish.

    Read the article

  • How to reduce redundant code when adding new c++0x rvalue reference operator overloads

    - by Inverse
    I am adding new operator overloads to take advantage of c++0x rvalue references, and I feel like I'm producing a lot of redundant code. I have a class, tree, that holds a tree of algebraic operations on double values. Here is an example use case: tree x = 1.23; tree y = 8.19; tree z = (x + y)/67.31 - 3.15*y; ... std::cout << z; // prints "(1.23 + 8.19)/67.31 - 3.15*8.19" For each binary operation (like plus), each side can be either an lvalue tree, rvalue tree, or double. This results in 8 overloads for each binary operation: // core rvalue overloads for plus: tree operator +(const tree& a, const tree& b); tree operator +(const tree& a, tree&& b); tree operator +(tree&& a, const tree& b); tree operator +(tree&& a, tree&& b); // cast and forward cases: tree operator +(const tree& a, double b) { return a + tree(b); } tree operator +(double a, const tree& b) { return tree(a) + b; } tree operator +(tree&& a, double b) { return std::move(a) + tree(b); } tree operator +(double a, tree&& b) { return tree(a) + std::move(b); } // 8 more overloads for minus // 8 more overloads for multiply // 8 more overloads for divide // etc which also has to be repeated in a way for each binary operation (minus, multiply, divide, etc). As you can see, there are really only 4 functions I actually need to write; the other 4 can cast and forward to the core cases. Do you have any suggestions for reducing the size of this code? PS: The class is actually more complex than just a tree of doubles. Reducing copies does dramatically improve performance of my project. So, the rvalue overloads are worthwhile for me, even with the extra code. I have a suspicion that there might be a way to template away the "cast and forward" cases above, but I can't seem to think of anything.

    Read the article

  • Visual C++ 2010, rvalue reference bug?

    - by Sergey Shandar
    Is it a bug in Visual C++ 2010 or right behaviour? template<class T> T f(T const &r) { return r; } template<class T> T f(T &&r) { static_assert(false, "no way"); return r; } int main() { int y = 4; f(y); } I thought, the function f(T &&) should never be called but it's called with T = int &. The output: main.cpp(10): error C2338: no way main.cpp(17) : see reference to function template instantiation 'T f<int&>(T)' being compiled with [ T=int & ] Update 1 Do you know any C++x0 compiler as a reference? I've tried comeau online test-drive but could not compile r-value reference. Update 2 Workaround (using SFINAE): #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_reference.hpp> template<class T> T f(T &r) { return r; } template<class T> typename ::boost::disable_if< ::boost::is_reference<T>, T>::type f(T &&r) { static_assert(false, "no way"); return r; } int main() { int y = 4; f(y); // f(5); // generates "no way" error, as expected. }

    Read the article

  • C++ rvalue temporaries in template

    - by aaa
    hello. Can you please explain me the difference between mechanism of the following: int function(); template<class T> void function2(T&); void main() { function2(function()); // compiler error, instantiated as int & const int& v = function(); function2(v); // okay, instantiated as const int& } is my reasoning correct with respect to instantiation? why is not first instantiated as const T&? Thank you

    Read the article

  • C++0x Overload on reference, versus sole pass-by-value + std::move?

    - by dean
    It seems the main advice concerning C++0x's rvalues is to add move constructors and move operators to your classes, until compilers default-implement them. But waiting is a losing strategy if you use VC10, because automatic generation probably won't be here until VC10 SP1, or in worst case, VC11. Likely, the wait for this will be measured in years. Here lies my problem. Writing all this duplicate code is not fun. And it's unpleasant to look at. But this is a burden well received, for those classes deemed slow. Not so for the hundreds, if not thousands, of smaller classes. ::sighs:: C++0x was supposed to let me write less code, not more! And then I had a thought. Shared by many, I would guess. Why not just pass everything by value? Won't std::move + copy elision make this nearly optimal? Example 1 - Typical Pre-0x constructor OurClass::OurClass(const SomeClass& obj) : obj(obj) {} SomeClass o; OurClass(o); // single copy OurClass(std::move(o)); // single copy OurClass(SomeClass()); // single copy Cons: A wasted copy for rvalues. Example 2 - Recommended C++0x? OurClass::OurClass(const SomeClass& obj) : obj(obj) {} OurClass::OurClass(SomeClass&& obj) : obj(std::move(obj)) {} SomeClass o; OurClass(o); // single copy OurClass(std::move(o)); // zero copies, one move OurClass(SomeClass()); // zero copies, one move Pros: Presumably the fastest. Cons: Lots of code! Example 3 - Pass-by-value + std::move OurClass::OurClass(SomeClass obj) : obj(std::move(obj)) {} SomeClass o; OurClass(o); // single copy, one move OurClass(std::move(o)); // zero copies, two moves OurClass(SomeClass()); // zero copies, one move Pros: No additional code. Cons: A wasted move in cases 1 & 2. Performance will suffer greatly if SomeClass has no move constructor. What do you think? Is this correct? Is the incurred move a generally acceptable loss when compared to the benefit of code reduction?

    Read the article

  • Rvalues in C++03

    - by DeadMG
    How can you tell whether or not a given parameter is an rvalue in C++03? I'm writing some very generic code and am in need of taking a reference if possible, or constructing a new object otherwise. Can I overload to take by-value as well as by-reference and have the rvalue returns call the by-value function? Or do I have a very sickening feeling that this is why rvalue references are in C++0x?

    Read the article

  • Why is T() = T() allowed?

    - by Rimo
    I believe the expression T() creates an rvalue (by the Standard). However, the following code compiles (at least on gcc4.0): class T {}; int main() { T() = T(); } I know technically this is possible because member functions can be invoked on temporaries and the above is just invoking the operator= on the rvalue temporary created from the first T(). But conceptually this is like assigning a new value to an rvalue. Is there a good reason why this is allowed? Edit: The reason I find this odd is it's strictly forbidden on built-in types yet allowed on user-defined types. For example, int(2) = int(3) won't compile because that is an "invalid lvalue in assignment". So I guess the real question is, was this somewhat inconsistent behavior built into the language for a reason? Or is it there for some historical reason? (E.g it would be conceptually more sound to allow only const member functions to be invoked on rvalue expressions, but that cannot be done because that might break some existing code.)

    Read the article

  • rvalues and temporary objects in the FCD

    - by FredOverflow
    It took me quite some time to understand the difference between an rvalue and a temporary object. But now the final committee draft states on page 75: An rvalue [...] is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object. I can't believe my eyes. This must be an error, right?

    Read the article

  • Argument type deduction, references and rvalues

    - by uj2
    Consider the situation where a function template needs to forward an argument while keeping it's lvalue-ness in case it's a non-const lvalue, but is itself agnostic to what the argument actually is, as in: template <typename T> void target(T&) { cout << "non-const lvalue"; } template <typename T> void target(const T&) { cout << "const lvalue or rvalue"; } template <typename T> void forward(T& x) { target(x); } When x is an rvalue, instead of T being deduced to a constant type, it gives an error: int x = 0; const int y = 0; forward(x); // T = int forward(y); // T = const int forward(0); // Hopefully, T = const int, but actually an error forward<const int>(0); // Works, T = const int It seems that for forward to handle rvalues (without calling for explicit template arguments) there needs to be an forward(const T&) overload, even though it's body would be an exact duplicate. Is there any way to avoid this duplication?

    Read the article

  • Why is T() = T() allowed in C++?

    - by Rimo
    I believe the expression T() creates an rvalue (by the Standard) However the following code compiles (at least on gcc4.0) class T {... }; int main() { T() = T(); } I know technically this is possible because member functions can be invoked on temporaries and the above is just invoking the operator= on the r-value temporary created from T(). But conceptually this is like assigning a new value to an r-value. Is there a good reason why this is allowed?

    Read the article

  • Difference between c++11 vs c++03

    - by aiao
    I have spend a few hours about rvalue s and lvalue. Here is what I understand int main() { //..... Foo foo = Bar1(); Foo foo = Bar2(); //...... } Foo Bar1() { //Do something return foo; } Foo& Bar2() { //Do something return foo; } Under c++03, Bar1() would copy the return object (just before return), and then return the address of the copied object; executing a wasteful copy of an object which is about to be destroyed. Bar2() would return the object created within the function. Under c++11, Bar1() and Bar2() would essentially be equivalent (and also equivalent to Bar2() of c++03). Is that right? If not, please elaborate.

    Read the article

  • Problem with "moveable-only types" in VC++ 2010

    - by Luc Touraille
    I recently installed Visual Studio 2010 Professional RC to try it out and test the few C++0x features that are implemented in VC++ 2010. I instantiated a std::vector of std::unique_ptr, without any problems. However, when I try to populate it by passing temporaries to push_back, the compiler complains that the copy constructor of unique_ptr is private. I tried inserting an lvalue by moving it, and it works just fine. #include <utility> #include <vector> int main() { typedef std::unique_ptr<int> int_ptr; int_ptr pi(new int(1)); std::vector<int_ptr> vec; vec.push_back(std::move(pi)); // OK vec.push_back(int_ptr(new int(2)); // compiler error } As it turns out, the problem is neither unique_ptr nor vector::push_back but the way VC++ resolves overloads when dealing with rvalues, as demonstrated by the following code: struct MoveOnly { MoveOnly() {} MoveOnly(MoveOnly && other) {} private: MoveOnly(const MoveOnly & other); }; void acceptRValue(MoveOnly && mo) {} int main() { acceptRValue(MoveOnly()); // Compiler error } The compiler complains that the copy constructor is not accessible. If I make it public, the program compiles (even though the copy constructor is not defined). Did I misunderstand something about rvalue references, or is it a (possibly known) bug in VC++ 2010 implementation of this feature?

    Read the article

  • Why is rvalue write in shared memory array serialised?

    - by CJM
    I'm using CUDA 4.0 on a GPU with computing capability 2.1. One of my device functions is the following: device void test(int n, int* itemp) // itemp is shared memory pointer { const int tid = threadIdx.x; const int bdim = blockDim.x; int i, j, k; bool flag = 0; itemp[tid] = 0; for(i=tid; i<n; i+=bdim) { // { code that produces some values of "flag" } } itemp[tid] = flag; } Each thread is checking some conditions and producing a 0/1 flag. Then each thread is writing flag at the tid-th location of a shared int array. The write statement "itemp[tid] = flag;" gets serialized -- though "itemp[tid] = 0;" is not. This is causing huge performance lag which technically should not be there -- I want to avoid it. Please help.

    Read the article

  • How can I get this code involving unique_ptr to compile?!

    - by Neil G
    #include <vector> #include <memory> using namespace std; class A { public: A(): i(new int) {} A(A const& a) = delete; A(A &&a): i(move(a.i)) {} unique_ptr<int> i; }; class AGroup { public: void AddA(A &&a) { a_.emplace_back(move(a)); } vector<A> a_; }; int main() { AGroup ag; ag.AddA(A()); return 0; } does not compile... (says that unique_ptr's copy constructor is deleted) I tried replacing move with forward. Not sure if I did it right, but it didn't work for me.

    Read the article

  • Function with parameter type that has a copy-constructor with non-const ref chosen?

    - by Johannes Schaub - litb
    Some time ago I was confused by the following behavior of some code when I wanted to write a is_callable<F, Args...> trait. Overload resolution won't call functions accepting arguments by non-const ref, right? Why doesn't it reject in the following because the constructor wants a Test&? I expected it to take f(int)! struct Test { Test() { } // I want Test not be copyable from rvalues! Test(Test&) { } // But it's convertible to int operator int() { return 0; } }; void f(int) { } void f(Test) { } struct WorksFine { }; struct Slurper { Slurper(WorksFine&) { } }; struct Eater { Eater(WorksFine) { } }; void g(Slurper) { } void g(Eater) { } // chooses this, as expected int main() { // Error, why? f(Test()); // But this works, why? g(WorksFine()); } Error message is m.cpp: In function 'int main()': m.cpp:33:11: error: no matching function for call to 'Test::Test(Test)' m.cpp:5:3: note: candidates are: Test::Test(Test&) m.cpp:2:3: note: Test::Test() m.cpp:33:11: error: initializing argument 1 of 'void f(Test)' Can you please explain why one works but the other doesn't?

    Read the article

  • Output is different for R-value and L-value. Why?

    - by Leonid Volnitsky
    Can someone explain to me why output for R-value is different from L-value? #include <iostream> #include <vector> using namespace std; template<typename Ct> struct ct_wrapper { Ct&& ct; // R or L ref explicit ct_wrapper(Ct&& ct) : ct(std::forward<Ct>(ct)) { std::cout << this->ct[1];}; }; int main() { // L-val vector<int> v{1,2,3}; ct_wrapper<vector<int>&> lv(v); cout << endl << lv.ct[0] << lv.ct[1] << lv.ct[2] << endl; // R-val ct_wrapper<vector<int>&&> rv(vector<int>{1,2,3}); cout << endl << rv.ct[0] << rv.ct[1] << rv.ct[2] << endl; } Output (same for gcc48 and clang32): 2 123 2 003

    Read the article

  • Show RGB888 content

    - by Abhi
    Hi all! I have to show RGB888 content using the ShowRGBContent function. The below function is a ShowRGBContent function for yv12-rgb565 & UYVY-RGB565 static void ShowRGBContent(UINT8 * pImageBuf, INT32 width, INT32 height) { LogEntry(L"%d : In %s Function \r\n",++abhineet,WFUNCTION); UINT16 * temp; BYTE rValue, gValue, bValue; // this is to refresh the background desktop ShowWindow(GetDesktopWindow(),SW_HIDE); ShowWindow(GetDesktopWindow(),SW_SHOW); for(int i=0; i<height; i++) { for (int j=0; j< width; j++) { temp = (UINT16 *) (pImageBuf+ i*width*PP_TEST_FRAME_BPP+j*PP_TEST_FRAME_BPP); bValue = (BYTE) ((*temp & RGB_COMPONET0_MASK) >> RGB_COMPONET0_OFFSET) << (8 -RGB_COMPONET0_WIDTH); gValue = (BYTE) ((*temp & RGB_COMPONET1_MASK) >> RGB_COMPONET1_OFFSET) << (8 -RGB_COMPONET1_WIDTH); rValue = (BYTE) ((*temp & RGB_COMPONET2_MASK) >> RGB_COMPONET2_OFFSET) << (8 -RGB_COMPONET2_WIDTH); SetPixel(g_hDisplay, SCREEN_OFFSET_X + j, SCREEN_OFFSET_Y+i, RGB(rValue, gValue, bValue)); } } Sleep(2000); //sleep here to review the result LogEntry(L"%d :Out %s Function \r\n",++abhineet,__WFUNCTION__); } I have to modify this for RGB888 Here in the above function: ************************ RGB_COMPONET0_WIDTH = 5 RGB_COMPONET1_WIDTH = 6 RGB_COMPONET2_WIDTH = 5 ************************ ************************ RGB_COMPONET0_MASK = 0x001F //31 in decimal RGB_COMPONET1_MASK = 0x07E0 //2016 in decimal RGB_COMPONET2_MASK = 0xF800 //63488 in decimal ************************ ************************ RGB_COMPONET0_OFFSET = 0 RGB_COMPONET1_OFFSET = 5 RGB_COMPONET2_OFFSET = 11 ************************ Also PP_TEST_FRAME_BPP = 2 for yv12 -> RGB565 & UYVY -> RGB565 Now my task is for RGB888. Please guide me what shall i do in this. Thanks in advance.

    Read the article

1 2 3  | Next Page >