简体   繁体   English

右值和左值的重载函数

[英]Overload function for rvalues and lvalues

I am writing a library that uses shared pointers to build a complex structure of nodes. 我正在编写一个使用共享指针来构建节点的复杂结构的库。 Since there can be cycles in the structure, and to avoid memory leakes, I decided to adopt the following strategy when building the structure: whenever I am passed a temporary object, I use a shared_ptr (to get the ownership); 由于结构中可能存在周期,并且为了避免内存泄漏,因此我决定在构建结构时采用以下策略:每当我传递一个临时对象时,我就使用shared_ptr(获取所有权); whenever I am passed a lvalue, I use a weak_ptr. 每当我传递左值时,我都会使用weak_ptr。 According to my analysis and the way the library interface is designed, this should avoid cycles altogether. 根据我的分析和库接口的设计方式,这应该完全避免循环。

However, I am having problems in using function overloading to understand when the parameter is a rvalue or a lvalue. 但是,在使用函数重载来了解参数是右值还是左值时,我遇到了问题。 Here is a very simplified example of the error I get: 这是我得到的错误的非常简化的示例:

#include <iostream>
#include <memory>

using namespace std;

class MyClass {
public:
    int a;
    // this class contains some pointers to the node structure
};

MyClass fun(MyClass &&x, MyClass &&y)
{
    // should produce an object that has ownership of the two others
}

MyClass fun(MyClass x, MyClass y)
{
    // should not take ownership, but just copy the pointer
}

int main()
{
    MyClass x, y;

    fun(x, y);
    fun(MyClass(), MyClass());
}

When compiling with g++ 4.8.2 I get the following error: 使用g ++ 4.8.2编译时,出现以下错误:

example.cpp: In function ‘int main()’:
example.cpp:29:29: error: call of overloaded ‘fun(MyClass, MyClass)’ is ambiguous
     fun(MyClass(), MyClass());
                             ^
example.cpp:29:29: note: candidates are:
example.cpp:12:9: note: MyClass fun(MyClass&&, MyClass&&)
 MyClass fun(MyClass &&x, MyClass &&y)
         ^
example.cpp:18:9: note: MyClass fun(MyClass, MyClass)
 MyClass fun(MyClass x, MyClass y)
         ^

So, apparently the compiler cannot distinguish between the two calls. 因此,显然编译器无法区分这两个调用。 I thought the rvalue function has precedence over the pass-by-value function, but evidently I was wrong. 我以为rvalue函数优先于pass-by-value函数,但显然我错了。

Also: I cannot declare the function to take const references, because I want just to take ownership and then later modify the object at will, so the reference should not be constant. 另外:我不能声明该函数接受const引用,因为我只想获取所有权,然后在以后随意修改该对象,因此引用不应为常量。

Any ideas on how I may solve this problem? 关于如何解决此问题的任何想法?

Change: 更改:

MyClass fun(MyClass x, MyClass y)
MyClass fun(MyClass&& x, MyClass&& y)

To: 至:

MyClass fun(MyClass& x, MyClass& y)      // for lvalues
MyClass fun(MyClass&& x, MyClass&& y)    // for rvalues

In your original example, the temporary MyClass could bind to either a value or an rvalue reference (both are exact matches). 在您的原始示例中,临时MyClass可以绑定到值或右值引用(两者都是完全匹配)。 But with the change, there's no ambiguity. 但是有了变化,就没有歧义了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM