【发布时间】:2016-02-04 11:02:53
【问题描述】:
考虑下面的模板类
template <typename T>
class A {
public:
virtual T const& getContent() = 0;
};
我使用'int*'作为类型'T'派生这个类,如下
class A1 : public A<int*> {
private:
int a;
public:
int* const& getContent() { return &a; }
};
我收到以下警告:'返回对本地临时对象的引用'。
问题:
编译器是否在返回其引用之前从“&a”隐式实例化“int * const”类型的本地临时对象?
我知道 A.a 确实存在,那么我可以忽略这个警告吗?使用此代码会不会有任何不良副作用?
处理这种情况的正确方法是什么?我是否需要使用成员变量 'int *a' 来代替。这会很麻烦。
【问题讨论】:
-
T const& getContent() = 0:你是说virtual T const& getContent() = 0吗? -
getContent函数也应该声明为const。
标签: c++