考虑下面的代码:右值引用,指针和拷贝构造函数
int three() {
return 3;
}
template <typename T>
class Foo {
private:
T* ptr;
public:
void bar(T& t) { ptr = new T(t); }
void bar(const T& t) { ptr = new T(t); }
void bar(T&& t) { (*ptr) = t; } // <--- Unsafe!
};
int main() {
Foo<int> foo;
int a = 3;
const int b = 3;
foo.bar(a); // <--- Calls Foo::bar(T& t)
foo.bar(b); // <--- Calls Foo::bar(const T& t)
foo.bar(three()); // <--- Calls Foo::bar(T&& t); Runs fine, but only if either of the other two are called first!
return 0;
}
我的问题是,为什么第三超载Foo::bar(T&& t)
崩溃的程序?到底发生了什么?函数返回后参数t
是否被破坏?
此外,我们假设模板参数T
是一个非常大的对象,其拷贝构造函数非常昂贵。有没有办法使用RValue引用来将它分配给Foo::ptr
而不直接访问这个指针并复制?
你写的代码不会导致任何问题(除了内存泄漏,并不实际编译)。那是你正在使用的实际代码吗? –
它编译好**和**运行良好:http://ideone.com/Ypqxz – Nawaz
这确切的代码似乎在Visual Studio 2010中正常工作(尽管存在内存泄漏)。你确定你的编译器版本是否符合右值引用? – Chad