About std::move
, here is what I can interpret, according to http://en.cppreference.com/w/cpp/utility/move :-
- If I want to transfer ownership, I have to call
std::move
(or in rare case,std::forward
). - Responsibility of
std::move
is callingoperator=(A&& other)
. - The most essential step of the move operation is supposed to be implemented in
operator=(A&&)
. - It is tricky to ensure that
operator=(A&&)
would be called. It need a special converter. - There are only two converters in the C++ world that can convert variables into
xvalue
(the &&) :std::move
andstd::forward
.
Question
After adding many of std::move(std::unique_ptr)
in my code, I start to worry that for such basic feature like transfer ownership, I have to heavily rely on the standard library (std::
).
Do I really have to use std::move
to transfer ownership?
Is spamming and hard-code calling std::move
in many places of code-base a correct way to go for a high-standard program?
Should std::move
be encapsulated?
They are actually a single question, but ask in different perspectives.
Edit
As request, here is my trial & error. It compiled ok.
I have no problem about the code, but I worry about its approach / pattern.
https://ideone.com/y8Pcgf
class T{
public: int value;
public: T(int a=1234){
value = a;
}
};
int main() {
std::unique_ptr<T> t1 = std::unique_ptr<T>(new T(1));
void* databaseNew=operator new [](sizeof(std::unique_ptr<T>));
std::unique_ptr<T>* t1ptr=static_cast<std::unique_ptr<T>*>(databaseNew);
new (t1ptr) std::unique_ptr<T>(std::move(t1));
return 0;
}