我在编译时遇到上述错误,我该如何纠正。请帮我解决这个问题
#include <iostream>
using namespace std;
template <typename T>
class bar
{
public:
bar(){cout << "bar" <<"\n";}
};
template <typename T, typename ctor = bar<T>>
class foo
{
T i;
public:
explicit foo(ctor& c = ctor());
private:
ctor mctor;
};
template <typename T, typename ctor>
foo<T,ctor>::foo(ctor& c):mctor(c)
{
cout << "foo" <<"\n";
}
int main()
{
foo<int> f;
return 0;
}
编译:g ++ -std = c ++ 11 ctor_call.cpp
您正在为应该在此行中通过引用传递的参数提供默认参数:
explicit foo(ctor& c = ctor());
在这里,ctor&
是对type对象的引用ctor
。因此,该对象需要一直存在,只要您有对其的引用即可。但是默认参数将其设置为一个即将被销毁的临时对象。而且由于临时对象不是标准化的,因此可以在构造函数开始之前将其销毁,因此您将一无所获。这个答案对所有这些都有很好的解释。
模板使您的案例更加复杂,因此让我们更具体一些。默认ctor()
是对您要引用的对象的构造函数的调用。在您的情况下,类为foo<int>
,因此模板看起来像
template <int, typename ctor = bar<int>>
class foo
在这里,模板将获得第二个参数,但这是默认参数,因此您获得了ctor = bar<int>
。这等同于使用foo<int, bar<int>>
。现在,在您的函数语句中,ctor()
实际上与bar<int>()
-相同,它是对构造函数的调用。
1)不要通过默认值:
explicit foo(ctor& c);
2)不要通过引用传递:
explicit foo(ctor c = ctor());
3)通过const引用传递:
explicit foo(const ctor& c = ctor());
这有点神奇,因为它const
使编译器保留临时对象,直到const引用销毁为止,该常量引用在foo
构造函数调用的末尾出现。
4)使用foo
对象外部存在的东西,例如静态或全局对象。(尽管您应该对静态保持警惕,并且我们基本上都讨厌全局变量...):
explicit foo(ctor& c = some_ctor_object_that_exists_already);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句