c++ - 将函数声明为 BigStruct&& foo(...) 是一种好习惯吗?

标签 c++ rvalue

<分区>

class A
{
public:
    A()
    {
        cout << "A()" << endl;
    }

    A(const A&)
    {
        cout << "A(const A&)" << endl;
    }

    A(A&&)
    {
        cout << "A(A&&)" << endl;
    }

    A& operator=(const A&)
    {
        cout << "A(const A&)" << endl;
    }

    A& operator=(A&&)
    {
        cout << "A(const A&&)" << endl;
    }

    ~A()
    {
        cout << "~A()" << endl;
    }
};

A&& f_1()
{
    A a;
    return static_cast<A&&>(a);
}

A f_2()
{
    A a;
    return static_cast<A&&>(a);
}

int main()
{
    cout << "f_1:" << endl;
    f_1();
    cout << "f_2:" << endl;
    f_2();
}

输出是:

f_1:
A()
~A()
f_2:
A()
A(A&&)
~A()
~A()

示例代码明显表明 f_1() 比 f_2() 更高效。

所以,我的问题是:

我们是否应该始终将函数声明为 some_return_type&& f(...);而不是 some_return_type f(...); ?

如果我的问题的答案是正确的,那么接下来是另一个问题:

已经有很多函数声明为 some_return_type f(...);在 C++ 世界中,我们应该将它们更改为现代形式吗?

最佳答案

Is it a good practice that declaring a function as BigStruct&& foo(…);

可怕的做法。与 lvalue-references 一样,您所做的是将 reference 返回给本地对象。当调用者收到引用时,引用的对象已经不存在了。

There have been many many functions declared as some_return_type f(...); in the C++ world, should we change them to the modern form?

现代形式是它们已经构建的形式(仅考虑返回类型)。更改标准是为了使通用形式更高效,而不是让每个人都重写所有代码。

现在有一些非现代版本,比如 void f( type& t ) 而不是 type f() when f < em>创建对象。我们希望将那些更改为现代形式 type f(),因为它提供了一个更简单的接口(interface)来推理并提供更简单的用户代码:

用户不需要考虑对象是修改还是创建:

void read_input( std::vector<int>& );

这是附加还是替换 vector ?

并使调用者代码更简单:

auto read_input();

对比

std::vector<int> v; 
read_input(v);

关于c++ - 将函数声明为 BigStruct&& foo(...) 是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10463535/

相关文章:

C++:创建映射到枚举的某种类型的对象

c++ - 关于纯抽象类中的静态成员函数 - 设计模式?

c++ - 具有通用引用/完美转发的 Boost.python?

android - JNI 调用将 jstring 转换为 char*

c++ - 设置类成员 unique_ptr<T[]> 数组而不复制

c++ - 为什么对象在 std::move 函数之后仍然存在?

c++ - 为什么不允许仅对一个 ref-qualifier 进行重载?

c++ - 从 .rdata 部分删除 IMAGE_DEBUG_DIRECTORY

c++ - 为什么 const double && 不适用于左值引用?

c++ - 插入无序映射调用构造函数