Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 重载箭头运算符为ref合格_C++_Operator Overloading - Fatal编程技术网

C++ 重载箭头运算符为ref合格

C++ 重载箭头运算符为ref合格,c++,operator-overloading,C++,Operator Overloading,如果我的类的arrow操作符返回一个指向内部数据的指针,始终将其声明为ref-qualified,并使其仅用于l值,这是一个好主意吗 template <class T> class Dummy { T _data; // data lives within the class public: Dummy() { /* some ctor logic */ } T* operator->() & { return &_data; } //

如果我的类的arrow操作符返回一个指向内部数据的指针,始终将其声明为ref-qualified,并使其仅用于l值,这是一个好主意吗

template <class T>
class Dummy
{
  T _data; // data lives within the class

public:
  Dummy() { /* some ctor logic */ }

  T* operator->() & { return &_data; }
  //              ^ this is the question

  T const* operator->() const& { return &_data; }
  //                         ^ this is the question
};
模板
类虚拟
{
T_data;//数据存在于类中
公众:
Dummy(){/*某些ctor逻辑*/}
T*运算符->()&{return&_data;}
//^这就是问题所在
T常量*运算符->()常量&{return&_data;}
//^这就是问题所在
};
这背后的原因是,在临时实例上使用arrow操作符默认情况下会创建一个悬空指针,因为数据存在于我的类中

另外,在ref限定符和重载成员访问操作符上是否有规范资源



请注意,提供的类示例纯粹是为了演示,以提供一个最小的示例。

临时类的生存期将扩展到创建它的整个完整表达式,因此在例如,
Wrapper()->size()中不会有悬空指针
这是否有用取决于
T
和包装的目的。@molbdnilo我有一个说明,首先“包装器”类只是一个例子。我没有包装,这个问题涉及到“重载箭头操作符”。数据存在于类中,可能会发生生存期扩展,但在函数调用中也可能有人将指针存储在类中(不提供生存期扩展)。我明白你的观点,这一切都取决于使用,但有什么具体的指导方针吗?我能想到的最具体的指导方针是“不要向内部数据分发指针,特别是不要隐藏在方便的语法后面”和“试图防止所有可能的错误会增加很多复杂性,但收效甚微”。