C++ 双地址运算符? (&&)

标签 c++ stl operator-keyword memory-address

我正在阅读 STL 源代码,但我不知道 && 地址运算符应该做什么。这是 STL_vector.h 中的代码示例:

vector&
operator=(vector&& __x) // <-- Note double ampersands here
{
    // NB: DR 675.
    this->clear();
    this->swap(__x); 
    return *this;
}

“地址的地址”有意义吗?为什么它有两个地址运算符而不是一个?

最佳答案

&& 是 C++11 中的新内容。 int&& a 表示“a”是一个右值引用。 && 通常只用于声明函数的参数。它采用右值表达式。如果你不知道什么是 r 值,简单的解释是它没有内存地址。例如。数字 6 和字符“v”都是 r 值。 int a,a 是左值,而 (a+2) 是右值。例如:

void foo(int&& a)
{
    //Some magical code...
}

int main()
{
    int b;
    foo(b); //Error. An rValue reference cannot be pointed to a lValue.
    foo(5); //Compiles with no error.
    foo(b+3); //Compiles with no error.

    int&& c = b; //Error. An rValue reference cannot be pointed to a lValue.
    int&& d = 5; //Compiles with no error.
}

希望能提供信息。

关于C++ 双地址运算符? (&&),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549151/

相关文章:

c# - C++ 中的 String.Format 替代方案

c++ - 为什么自制的二进制搜索算法比 std::binary_search 慢?

c++ - 来自 std::unordered_map 的以下命令之间是否有任何区别

c++ - STL::multimap - 我如何获取数据组?

c++ - 无需显式类型转换的运算符重载

java - 在 if 语句中使用按位 &

c# - StackOverflow 在设计比较运算符时

c++ - 带字符的矩阵

C++ 自定义迭代器和范围问题

c++ - boost::numeric::ublas::vector 内部数据存储指针