如何返回指针指向的值
How do I return the value pointed to by a pointer?
我有一个类成员定义为:
someType* X;
我得到它像:
someType* getX() {return x;}
我想获取值而不是指针,即:
someType getX() {return x;} //this is wrong
正确的语法是什么?如何获取值而不是指针?
someType getX() {return *x;}
请注意,这按值返回x
,即它在每次返回时创建一个x
的副本*。因此(取决于someType
到底是什么)您可能更喜欢返回引用:
someType& getX() {return *x;}
对于构造成本可能很高的非基元类型,建议通过引用返回,并且对象的隐式复制可能会引入细微的错误。
*在某些情况下,这可以通过返回值优化来优化,如下@paul23正确指出的那样。但是,一般而言,安全行为并不指望这一点。如果您不希望创建额外的副本,请在代码中通过返回引用(或指针)为编译器和人类读者明确说明。
someType getX() const { return *x; }
或者,如果复制someType
成本很高,请通过const
引用将其返回:
someType const &getX() const { return *x; }
请注意,该方法const
限定符。
SomeType getX()
{
// SomeType x = *x; // provided there is a copy-constructor if
// user-defined type.
// The above code had the typo. Meant to be.
SomeType y = *x;
return y;
}
相关文章:
- 何时返回指针与返回对象的一般经验法则?
- 在函数内初始化无符号字符指针将返回空指针
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- void 函数中的指针参数返回不一致的值
- void *function() 是指向函数的指针还是返回 void* 的函数?
- c++:何时传递指针与返回对象
- C++:私有类指针成员返回未定义的值
- 在字符串函数的指针中返回地址
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 我的问题是关于类成员函数作为类指针的返回类型
- 防止编码器错误 - 通过参考(悬挂指针)返回临时值
- 为什么指向 c 字符串中元素的指针不只返回元素?
- ::运算符 delete(指针) 返回释放的字节大小
- 在参数包中获取函数指针的返回类型,并将其保存为与其他参数连接的元组
- 我正在尝试创建一个方法,该方法使用指针算术返回一对,它是否会出错
- 返回指针、返回值或传入引用,这在C++中很优雅
- 为什么静态、非本地返回指针的返回值始终为零?
- 当父类共享指针为返回类型时返回新的基类
- 当返回类型不是指针时返回NULL
- C++ 返回指针与返回带有 std::move 的本地对象