Learn About The Initialization Of Class Objects By Rvalues In C++ Windows Development
C++Builder includes the use of rvalue references, which allow creating a reference to temporaries. When you initialize to an class object using an rvalue(a temporary object), C++11 looks to see if you have defined a move constructor in your class. If you have, the temporary object is passed to it as a modifiable (non-const) rvalue reference, allowing you to transfer ownership of resource pointers and handles, and nullify them in the temporary object.
We can implement the move constructor as follows.
public:
SomeClass() : foo(nullptr) {}
//Move Constructor
SomeClass(SomeClass &&c)
{
foo = c.foo;
c.foo = nullptr;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
SomeClass obj = SomeClass(50); //Move constructor is called.
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class SomeClass { private: int *foo;
public: SomeClass() : foo(nullptr) {} //Move Constructor SomeClass(SomeClass &&c) { foo = c.foo; c.foo = nullptr; } };
int _tmain(int argc, _TCHAR* argv[]) { SomeClass obj = SomeClass(50); //Move constructor is called.
return 0; } |
Here use the syntax && to indicate that the variable is an rvalue reference. When the temporary object is initialized, we now simply copy the pointer instead of the content it points to.
Head over and check out all of the C++ features supported by the Clang compiler in C++Builder.