simple question im not sure about

This is a discussion on simple question im not sure about within the C++ Programming forums, part of the General Programming Boards category; I have a simple function and string: Code: std::string test = "some string data..."; some_func(test); void some_func(std::string test) { } ...

  1. #1
    l2u
    l2u is offline
    Registered User
    Join Date
    May 2006
    Posts
    630

    simple question im not sure about

    I have a simple function and string:

    Code:
    std::string test = "some string data...";
    some_func(test);
    
    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
    Location
    Singapore
    Posts
    21,744
    Yes. As a replacement for your first function example, you could consider:
    Code:
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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
    Location
    Fuzhou University, Fujian, China
    Posts
    35
    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, 08:46 AM
  4. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 11:15 AM
  5. simple fgets question
    By theweirdo in forum C Programming
    Replies: 7
    Last Post: 01-27-2002, 05:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21