我正在编写一个使用共享指针来构建复杂节点结构的库.由于结构中可能存在循环,并且为了避免内存泄漏,我在构建结构时决定采用以下策略:每当我传递一个临时对象时,我都使用shared_ptr(获取所有权); 每当我通过左值时,我都会使用weak_ptr.根据我的分析和库接口的设计方式,这应该完全避免循环.
但是,我在使用函数重载时遇到问题,以了解参数是rvalue还是左值.这是我得到的错误的一个非常简单的例子:
#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());
}
Run Code Online (Sandbox Code Playgroud)
使用g ++ 4.8.2进行编译时出现以下错误:
example.cpp: In function …Run Code Online (Sandbox Code Playgroud)