结构化绑定和强制复制省略

时间:2017-01-21 21:36:56

标签: c++ c++17 copy-elision structured-bindings

如果你使用像这样的结构化绑定

// your code

try{
    //Database connection
    $conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");

    $result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
    while($row = $result->fetch_array()){

        $res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
        if($res->num_rows){
            // Update the existing row
            $conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
            echo "Affected rows: " . $conn->affected_rows . '<br />';
        }else{
            // Insert a new row
            $res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
            if($res) echo "New row inserted <br />";
        }
    }
}catch(Exception $e) {
    $json_out =  json_encode(array("result"=>0));
    echo $json_out; 
}
然后

将返回返回元组的副本,并且对象直接进入auto [a, b, c] = std::make_tuple(1, 10.0, "string object"s); ab或者初始化是否会从单个元组元素移动构造?我怀疑这会导致副本发生但我不确定标准中强制复制省略的描述是否处理这种情况。

1 个答案:

答案 0 :(得分:4)

this excellent answer所述,声明相当于:

auto e = std::make_tuple(1, 10.0, "string object"s);
int& a = get<0>(e);
double& b = get<1>(e);
std::string& c = get<2>(e);

除了没有名称e。在此上下文中,get函数会生成对所选项的左值引用。

在C ++ 17中,auto name = prvalue; is defined声明一个名为name的{​​{1}}对象,该对象用prvalue表达式初始化 - 没有中间的临时表是可以删除的与以前的版本一样。

换句话说,decltype(prvalue)声明的行为与:

完全相同
e

然后std::tuple<int, double, std::string> e {1, 10.0, "string object"s}; 引用该元组的元素。

注意:上面的解释对应于最新的C ++ 17草案源;当然,在C ++ 17最终确定之前,行为可能会发生变化。