c++ - 为什么 std::pair<int, int> 可以从 const std::pair<int, float>& 构造?

标签 c++

看来 std::pair<int, int>可以从 const std::pair<int, float>& 隐式构造使用 here 中的第四个定义.

#include <iostream>
#include <vector>
#include <utility>

int main() {
    std::vector<std::pair<int, float>> v = { {1, 1.5f} };

    // The interesting line:
    const std::pair<int, int>& x = v[0];

    const auto& y = v[0];

    std::cout << "before:\n";
    std::cout << "\tv[0]: " << std::get<1>(v[0]) << "\n";
    std::cout << "\tx:    " << std::get<1>(x) << "\n";
    std::cout << "\ty:    " << std::get<1>(y) << "\n";

    std::get<1>(v[0]) = 3.5f;

    std::cout << "\nafter:\n";
    std::cout << "\tv[0]: " << std::get<1>(v[0]) << "\n";
    std::cout << "\tx:    " << std::get<1>(x) << "\n";
    std::cout << "\ty:    " << std::get<1>(y) << "\n";
}

输出是

before:
    v[0]: 1.5
    x:    1
    y:    1.5

after:
    v[0]: 3.5
    x:    1
    y:    3.5

( ideone link )

x 看起来很尴尬“感觉”不像引用而不是 y (因为从用户的角度来看,它(合法地)引用了可能是“错误”的东西。)

构造函数未标记为 explicit 的原因是什么? ? (我假设有一个重要的用例。)

最佳答案

// The interesting line:
const std::pair<int, int>& x = v[0];

该代码等同于:

const std::pair<int,int>& x = std::pair<int,int>(v[0]);

令您感到惊讶的问题是,由于存在来自 std::pair<int,float> 的转换至 std::pair<int,int>允许(并且要求)编译器创建一个临时文件并将 const 引用绑定(bind)到它。如果删除 const (并且您没有使用 VS)代码应该会失败。

关于c++ - 为什么 std::pair<int, int> 可以从 const std::pair<int, float>& 构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20481496/

相关文章:

c++ - 无法找到未定义行为的原因

c++ - std::set C++ 的高效插入技术

c++ - Code::Blocks 可执行文件没有纹理

c++ - .*& 运算符是做什么的?

c++ - 使用 UDP 套接字字节限制的 header

c++ - 释放包含字符串变量的结构

c++11 在类定义中为可变大小 std::array 创建数据成员

c++ - 将 int 的单个数字存储在数组中

c++ - 为什么我不能在 SQLite 中的 VIEW 上创建触发器?

c++ - Opencv minMaxLoc 参数