Thread: simple question im not sure about

  1. #1
    Registered User
    Join Date
    May 2006

    simple question im not sure about

    I have a simple function and string:

    std::string test = "some string data...";
    void some_func(std::string test) {
    void some_func(std::string &test) {
    In the first case, the string will be copied when passed to function, and in the second case it will pass the reference (it wont copy the data)?

    Am I correct?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Yes. As a replacement for your first function example, you could consider:
    void some_func(const std::string& test) {
    So the string is not copied, but at the same time the caller is assured that the string passed will not be modified.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User zouyu1983's Avatar
    Join Date
    Nov 2006
    Fuzhou University, Fujian, China
    the first case : the compiler will call the copy-constructor to construct a temp string which the value is the same as the test, and when the function ends, the compiler will call the destructor
    to destory the temp string

    the second case is only passed a reference, and none of the constructor and destructor will be called. because existing a const, you can't modify the test value
    Hello, guys, i come from china, so i am not good at english. If you find the sentence i wrote full of mistakes, please tell me.
    I confirm that my english and programming skills will be improved with your help in this forum. thanks^_^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple question regarding variables
    By Flakster in forum C++ Programming
    Replies: 10
    Last Post: 05-18-2005, 08:10 PM
  2. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2005, 11:41 PM
  3. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 09:46 AM
  4. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  5. simple fgets question
    By theweirdo in forum C Programming
    Replies: 7
    Last Post: 01-27-2002, 06:58 PM