Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference type recommended usage

Tags:

c++

reference

I am programming in C++ more then 5 years, and have never met any place where reference of the variable is recommended to use except as a function argument (if you don't want to copy what you pass as your function argument). So could someone point cases where C++ variable reference is recommended (I mean it gives any advantage) to use.

like image 901
Narek Avatar asked Sep 26 '09 13:09

Narek


2 Answers

i would like to enlist some cases:

1) while writing singleton classes

 class singleton
    {
        singleton();
        explicit singleton(const singleton&);
        singleton& operator=(const singleton&);
    public:
        static singleton& instance()
        {
            static singleton inst;
            return inst;
        }
    };// this is called the 'Meyers' singleton pattern. refer to More Effective C++ by  Scott Meyers

it has all the benefits, but avoids using the new operator

**2)**here is no such thing as a null reference. A reference must always refer to some object. As a result, if you have a variable whose purpose is to refer to another object, but it is possible that there might not be an object to refer to, you should make the variable a pointer, because then you can set it to null. On the other hand, if the variable must always refer to an object, i.e., if your design does not allow for the possibility that the variable is null, you should probably make the variable a reference

**3)**Because a reference must refer to an object, C++ requires that references be initialized:

  string& rs;             // error! References must
                          // be initialized

  string s("xyzzy");

  string& rs = s;         // okay, rs refers to s

Pointers are subject to no such restriction

The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using it

**4)**Another important difference between pointers and references is that pointers may be reassigned to refer to different objects. A reference, however, always refers to the object with which it is initialized: ¤ Item M1, P10

  string s1("Nancy");
  string s2("Clancy");

  string& rs = s1;         // rs refers to s1

  string *ps = &s1;        // ps points to s1

  rs = s2;                 // rs still refers to s1,
                           // but s1's value is now
                           // "Clancy"

  ps = &s2;                // ps now points to s2;
                           // s1 is unchanged
like image 152
Satbir Avatar answered Sep 28 '22 22:09

Satbir


As a return value of an opaque collection accessor/mutator

The operator[] of std::map returns a reference.


To shorten the text needed to reference a variable

If you miss old-school with Foo do ... statement (that's Pascal syntax), you can write

 MyString &name = a->very->long_->accessor->to->member;
 if (name.upcase() == "JOHN") {
    name += " Smith";
 }

another example of this can be found in Mike Dunlavey's answer


To state that something is just a reference

References are also useful in wrapper objects and functors--i.e. in intermediate objects that logically contact no members but only references to them.

Example:

class User_Filter{
  std::list<User> const& stop_list;
  public: Functor (std::list<User> const& lst)
    : stop_list(lst) { }
  public: bool operator()(User const& u) const
    {  return stop_list.exists(u); }
};

find_if(x.begin(),x.end(),User_Filter(user_list));

The idea here that it's a compile error if you don't initialize a reference in constructor of such an object. The more checks in compile time--the better programs are.

like image 39
P Shved Avatar answered Sep 28 '22 21:09

P Shved