通过输出参数从 C++ 函数返回值

问题描述 投票:0回答:1

我想通过引用的外参数返回非原始类型(例如 std::vector)。

void foo(std::vector<int>& out_vec)
{
    out_vec = std::vector<int>{1, 2, 3};
}

int main()
{
    std::vector<int> v;
    foo(v);

    return 0;
}

此代码按预期编译并打印“1 2 3”,但我担心 foo() 中的对象 std::vector{1, 2, 3} 的生命周期。

也许这是正确的?

void foo(std::vector<int>& out_vec)
{
    out_vec = std::move(std::vector<int>{1, 2, 3});
}

int main()
{
    std::vector<int> v;
    foo(v);

    return 0;
}
c++ scope reference arguments move
1个回答
-1
投票

但我担心 foo() 中的对象 std::vector{1, 2, 3} 的生命周期。

std::vector<int>{1, 2, 3}
是一个右值表达式,这意味着将自动使用 move 赋值运算符
vector& operator=( vector&& other );
,即,您不需要在示例中显式写入
std::move

vector& operator=( vector&& other ); (since C++11)
© www.soinside.com 2019 - 2024. All rights reserved.