c++ - C++11 中返回 const 值类型对 move 语义的影响

标签 c++ c++11 constants move-semantics

我不清楚返回 const 值对 C++11 中 move 语义的影响。

这两个返回数据成员的函数有什么区别吗? const 在 C++11 中仍然是多余的吗?

int GetValueA() { return mValueA; }
const int GetValueB() { return mValueB; }

这些功能呢?

int GetValuesAB() { return mValueA + mValueB; }
const int GetValuesCD() { return mValueC + mValueD; }

最佳答案

调用按值返回的函数的表达式是纯右值。但是,没有非类非数组类型的 const 纯右值 (§5/6):

If a prvalue initially has the type “cv T,” where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

这意味着您对函数的两个定义之间没有区别。它返回 const int 还是仅返回 int 是无关紧要的,因为表达式永远不会是 const

但是,返回类类型时会有所不同。考虑以下示例:

struct foo
{
  void bar() { std::cout << "Hello" << std::endl; }
};

foo get_foo();

现在,如果我们调用 get_foo(),我们会得到一个临时的 foo 对象。这个纯右值不是const,我们可以在它上面调用非const成员函数,所以我们可以愉快地做get_foo().bar() .但是,我们可以像这样更改 get_foo 的声明:

const foo get_foo();

现在,表达式 get_foo() 是一个 const 纯右值(这是允许的,因为它是一个类类型),我们不能调用 bar 在它返回的临时对象上。

尽管如此,谈论非类类型的 move 语义是没有意义的,因为 int 永远不会被 move 。如果您返回一个 const 类类型,也不能从中 move ,因为它是 const。演示:

foo get_foo();
foo f(get_foo()); // Will call the move constructor

const foo get_foo();
foo f(get_foo()); // Will call the copy constructor

这是因为 const 纯右值不会绑定(bind)到非 const 右值引用, move 构造函数将其作为参数。

关于c++ - C++11 中返回 const 值类型对 move 语义的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15745359/

相关文章:

c++ - 使用 ARM 跨工具链进入同一文件中定义的函数时出现段错误

c++ - 错误 : ‘int’ is not a class, 结构或 union 类型`

c++ - 在 VC 2010 中禁用 C++0x 功能?

c++ - 避免在必须增加维度时重新分配 vector

c++ - 为什么tellp() 是一个非常量?

c++ - 为什么下面的代码段返回指针所指向的值而不是指针的地址?

python - 使用 numba 处理容器中多个常量的最佳方法?

c++ - 在 Go (golang) 和 C++ 之间交换数据结构(数组)

c++ makefile - 你如何处理混合源文件后缀的规则(例如.cpp和.cxx)

带 bo​​ost 的 C++11 占位符