在c ++中返回对象的最佳方式? [英] Best way to return an object in c++?

查看:122
本文介绍了在c ++中返回对象的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我谈到c ++时,我真的很讨厌,什么是更好的方式返回一个对象?我来自脚本世界,其中对象总是引用,我试图实现相同的概念...我基于这个,其中一个用户说:通过引用传递的指针在什么时候? 一个好的经验法则:当你必须使用引用时,你可以使用引用。

I'm pretty noobish when it comes to c++, what is the better way of returning an object? I'm coming from the scripting world where Objects are always references, and am trying to achieve the same notion ... I'm basing this off of When to pass by reference and when to pass by pointer in C++?, where one user stated: "A good rule of thumb: "Use references when you can and pointers when you have to"."

// basic layer class
class Layer { private: Channel channel; // NEVER NULL };

// return object by pointer
Channel *Layer::getChannel() {
    return &channel;
};

// return by reference
Channel& Layer::getChannel() {
    return channel;
};

第二个版本的问题是编译器会接受这一行:

The problem with the second version is that the compiler will accept this line:

Channel channel = layer.getChannel();  // creates a copy BAD

应该是:

Channel &channel = layer.getChannel();  // reference good

有没有办法强制第二个选项的调用者强制它不

Is there any way to enforce a caller of the second option to force it to not create a new channel, or is the first option better anyways, even if it will never be NULL?

推荐答案

您需要调整一个新的频道, Channel 类本身,以便它不可复制。如果它是可复制的,用户可以复制它,并且你所做的任何事都可以阻止它。

You need to adjust the Channel class itself so that it isn't copyable. If it is copyable, the user can copy it, and nothing you do can prevent it.

如果复制不是一个有意义的操作,那么你可以禁用。只需定义复制构造函数( Channel(const Channel&))和赋值运算符( Channel& operator =(const Channel&))为私有。那么任何复制类的尝试都会导致编译错误。

If copying is not a meaningful operation, then you can "disable" it. Simply define the copy constructor (Channel(const Channel&)) and the assignment operator (Channel& operator=(const Channel&)) to be private. Then any attempt at copying the class will result in a compile error.

另一方面,正如其他人所说,C ++不是你熟悉的脚本语言。一切都不是一个参考,你只是通过假装否定了一个痛苦的世界。在C ++中,通常在堆栈上分配对象,并通过值传递对象,而不是传递引用和指针。

On a side note, as others have mentioned, C++ is not the scripting languages you're familiar with. Everything is not a reference, and you're only setting yourself up for a world of pain by pretending otherwise. In C++, it is common to allocate objects on the stack, and pass objects by value, rather than passing references and pointers around.

这篇关于在c ++中返回对象的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆