gpt4 book ai didi

c++ - 使用 std::pair 优化返回值

转载 作者:行者123 更新时间:2023-11-27 23:43:10 25 4
gpt4 key购买 nike

我目前对 C++17 保证的 RVO 及其含义感到非常困惑。我了解要启动 NRVO,我需要确保

  1. 通过函数所有可能的返回路径返回一个对象的同一个实例

  2. 在调用端用函数调用初始化关联对象

考虑一个最简单的装饰类Widget,我想分配一对没有拷贝的Widget,然后返回它

#include<iostream>
#include<utility>

struct Widget {
Widget() { std::cerr << "Default ctor" << std::endl; }
explicit Widget(int i) { std::cerr << "custom ctor" << std::endl; }
Widget(Widget const &) { std::cerr << "copy ctor" << std::endl; }
Widget(Widget &&) { std::cerr << "move ctor" << std::endl; }
Widget &operator=(Widget const &) { std::cerr << "copy assign" << std::endl; }
Widget &operator=(Widget &&) { std::cerr << "move assign" << std::endl; }
int i_;
};

auto foo(){
std::pair<Widget,Widget> w; // default construction
auto &[w1,w2] = w;
// do something with w1 and w2
return w;
}

int main(){
auto f = foo();
}

没有复制,但现在我尝试使用 make_pair

auto foo(){
auto w = std::make_pair<Widget,Widget>({},{}); // Awkward syntax and move construction
auto &[w1,w2] = w;
// do something with w1 and w2
return w;
}

如果我想使用 make_pair,这真的是唯一可能的选择吗?与第一个函数相比,为什么要涉及移动构造?

最佳答案

我认为你问题的前提是错误的。

Is this really the only possible alternative if I want to use make_pair?

为什么要在这里使用 std::make_pair

auto w = std::make_pair<Widget,Widget>({},{}); // Awkward syntax and move construction

这确实是一个笨拙的语法。让我解释一下为什么我这么认为......

来自 cppreferencestd::make_pair 上(强调我的):

Creates a std::pair object, deducing the target type from the types of arguments.

std::make_pair 的唯一目的是推断其参数的类型,例如

std::pair<int,int> x;                         
x = std::pair<int,int>(3,3); // not nice
x = std::make_pair(3,3); // ok

当默认构造一对并且你知道它的类型时,你永远不必重复模板参数

std::pair<int,int> a = std::pair<int,int>();  // awkward 

当你想要非默认构造时都不是(只是不要使用 auto ,因为它的唯一效果是你必须在同一行代码的其他地方拼写类型)

std::pair<int,int> a{5,4}; // no move/copy

底线:

另一种方法是在不需要时不使用 std::make_pair

关于c++ - 使用 std::pair 优化返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52747770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com