Thread: returning reference from class

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    630

    returning reference from class

    Hello
    I have a simple question.

    Suppose I have:

    Code:
    class someclass {
    public:
      int &number() const { return m_number; } //this is okay
      std::string &str() const { return m_str; } //this aint okay
    private:
      int m_number;
      std::string m_str;
    };
    How do you professionals return string by reference this way (const - so that it cannot be modified inside the function)?

    Should I just do:
    Code:
    std::string &str() { return m_str; }
    instead?

    Thanks for help!

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If you don't want the string modified, then you could do:
    Code:
    
    const std::string &str() const { return m_str; }
    You probably shouldn't allow outside functions to modify the string anyways.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    630
    Either
    Code:
    const std::string &str() const { return m_str; }
    or
    Code:
    std::string &str() const { return m_str; }
    Will give error: cannot convert from 'const std::string' to 'std::string &'

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    What makes returning a non-const int reference ok, but a non-const string reference not?

    Anyway, I never return references from my getters, except in very special circumstances. Certainly not for value-like objects like string. It loses half the advantage of a getter. You can no longer change the underlying member's type.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    Registered User
    Join Date
    May 2006
    Posts
    630
    Quote Originally Posted by CornedBee View Post
    Anyway, I never return references from my getters, except in very special circumstances. Certainly not for value-like objects like string. It loses half the advantage of a getter.
    So you recomment me to return just values in this case? What kind of advantage it loses?

  6. #6
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The advantage it loses was in my last sentence.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  7. #7
    Registered User
    Join Date
    May 2006
    Posts
    630
    What does losing ability to change the underlying member's type mean?
    Can show an example please?

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It means that, if you later on, decide to change from a std::string to nonstd::gnirts, which does the same thing as std::string, but uses a different internal format [and thus is much better for what you use it for most of the time], you can't do that without also changing all the code that calls str() in your class - but if you "hide" the fact that the internal structure is a string [just deliver a copy of the string, rather than a reference], then the code calling str() won't have to change if you modify the underlying form of m_str.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by l2u View Post
    Either
    Code:
    const std::string &str() const { return m_str; }
    or
    Code:
    std::string &str() const { return m_str; }
    Will give error: cannot convert from 'const std::string' to 'std::string &'
    Well, sure. Inside a const function, all member variables act like they are const. So you can't return a non-const reference to a member from inside a const function. I don't believe you that the first example doesn't work. It should work fine.

  10. #10
    Registered User
    Join Date
    May 2006
    Posts
    630
    Quote Originally Posted by brewbuck View Post
    Well, sure. Inside a const function, all member variables act like they are const. So you can't return a non-const reference to a member from inside a const function. I don't believe you that the first example doesn't work. It should work fine.
    It does.. Sorry, I missed something

  11. #11
    Registered User
    Join Date
    May 2006
    Posts
    630
    Quote Originally Posted by matsp View Post
    It means that, if you later on, decide to change from a std::string to nonstd::gnirts, which does the same thing as std::string, but uses a different internal format [and thus is much better for what you use it for most of the time], you can't do that without also changing all the code that calls str() in your class - but if you "hide" the fact that the internal structure is a string [just deliver a copy of the string, rather than a reference], then the code calling str() won't have to change if you modify the underlying form of m_str.

    --
    Mats
    I've always used reference because I thought only about the preformance..
    So you all agree that its generally better to avoid returning references to strings?

  12. #12
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    It's better to avoid returning references to private members. That they're strings is irrelevant.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Don't return references to member variables. It doesn't matter if they are strings, array, structs or simple variables.

    If the compiler is clever, and you inline the function, it may skip the copying when there's no possibility of the data being abused. It does assume the compiler "understands" what's going on [const correctness helps here].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #14
    Registered User
    Join Date
    May 2006
    Posts
    630
    If I just return string by value I guess I shouldnt return const string? Is that right?

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You can, but you don't need to.
    Code:
    const std::string Help2()
    {
    	return "";
    }
    
    void Help()
    {
    	std::string s = Help2();
    }
    Visual Studio completely ignores the const there since it's a return-by-value. The Help function can use it however much it wants, but it cannot actually modify the original string that's returned (since it's return-by-value).

    Following also works:
    Code:
    const std::string& Help2()
    {
    	static std::string s = "";
    	return s;
    }
    
    void Help()
    {
    	std::string s = Help2();
    }
    Following does not work:
    Code:
    const std::string& Help2()
    {
    	static std::string s = "";
    	return s;
    }
    
    void Help()
    {
    	std::string& s = Help2(); // Add const and it will compile
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. returning class and struct members
    By simone.marras in forum C++ Programming
    Replies: 17
    Last Post: 03-16-2009, 11:10 AM
  3. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  4. How can I pass a reference from a array os a class
    By Nautilus in forum C++ Programming
    Replies: 7
    Last Post: 01-20-2003, 06:23 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM