我是 c++11 的新手,并试图理解std::moveand 的含义unique_ptr并编写了以下代码,我以两种不同的方式std::move在 aunique_ptr上使用这些代码:
void unique_ptr_plain_move() {
unique_ptr<int> intptr(new int(10));
unique_ptr<int> intptr2;
printf("*intptr = %d\n", *intptr);
intptr2 = std::move(intptr);
printf("*intptr2 = %d\n", *intptr2);
// as expected, crash here as we have already moved intptr's ownership.
printf("*intptr = %d\n", *intptr);
}
/////////////////////////////////////////////
void function_call_move(unique_ptr<int>&& intptr) {
printf("[func] *intptr = %d\n", *intptr);
}
void unique_ptr_function_call_move() {
unique_ptr<int> intptr(new int(10));
printf("*intptr = %d\n", *intptr);
function_call_move(std::move(intptr));
// this does not crash, intptr still has the …Run Code Online (Sandbox Code Playgroud) 我试图理解移动语义的概念并做了一些测试。我有以下功能:
// testing the move semantic when passing
// argument to be modified without copying
void process_copy( std::vector<int>&& aVec)
{
std::cout << "Move semantic\n";
aVec.push_back(42);
}
Run Code Online (Sandbox Code Playgroud)
现在在主要功能中,以下内容:
int main()
{
std::vector<int> w_vec = {1,2,3,4,5};
process_copy( std::move(w_vec));
}
Run Code Online (Sandbox Code Playgroud)
我希望w_vec现在是空的,因为我通过移动转换(将左值转换为右值)传递了它。但结果现在w_vec包含6 个元素(42 个已添加到向量中)。
我想念的东西?是std::vector可移动的物体吗?
对于某些类来说S,重载一元operator +(或者可能operator *是非指针式类)如下所示是不好的做法?
struct S { S && operator + () & noexcept { return std::move(*this); } };
Run Code Online (Sandbox Code Playgroud)
它的目标是发明速记std::move.
S a;
S b = +a;
// instead of
S c = std::move(a);
Run Code Online (Sandbox Code Playgroud)
假设我有一个包含大量不同类的项目,它集中使用了移动语义.所有类都不模仿任何算术对应物.
c++ operator-overloading rvalue-reference move-semantics perfect-forwarding
我测试了c ++ 11移动功能,但没有生效.谁能告诉我为什么?谢谢.代码如下:
class Base {
public:
Base() { cout << "Base" << endl;}
~Base() { cout << "~Base" << endl;}
Base(const Base& base) { cout << "Copy" << endl; }
Base& operator=(const Base& base) {cout << "operator=" << endl;}
Base(Base&& base) { cout << "move" << endl;}
Base& operator=(Base&& base) { cout << "move=" << endl;}
};
Base b;
Base&& GetResult() {
return std::move(b);
}
int main() {
Base&& tmp = GetResult();
cout << &b << endl;
cout << …Run Code Online (Sandbox Code Playgroud) 我正在努力使自己了解移动语义。我很困惑,因为我找不到为什么我们需要它,以及如何理想地使用它。
例如,当我们通过std :: move移动对象时,它将使对象变为nullptr。为什么会这样?另外,为什么std :: move将对象变成右值?这是怎么发生的?为什么在将std :: move与变量一起使用后,它没有用null填充,但是当我将其与vector之类的对象一起使用时,将其移动后,便用nullptr填充了它。
我希望有人逐步解释CPP的移动语义和其他语义。我读得越多,我就越困惑。它是CPP编程中最复杂的主题之一。
我现在正在学习 C++ 11 并且对 C++ 11 中表达式的值类别感到困惑。根据术语,左值是 W 的左上角,即 iM(或有时是 im),意思是“具有身份但不能移动从”。这真的让我很困惑。请考虑以下示例:
#include <iostream>
int main()
{
int a = 0, b = 1, c = 2;
a = std::move(b = c);
std::cout << a << '\n';
}
Run Code Online (Sandbox Code Playgroud)
这个例子编译得很好。
我们都知道赋值b = c是一个左值,那么“不能移动”是什么意思?请举例说明这一点!
谢谢!