Brian
Brian

Reputation: 255

C++ object constructor pass by const reference copying

When I pass an object to another object as a const reference, is there a copy made? I always assumed since I passed in the object by reference the member object itself was actually the object I passed in and not a copy. I made a test program that causes the passed in reference object to be destroyed at the end of scope, but it doesn't crash as I expected. Is this a bug waiting to happen or is the object getting copied?

#include <iostream>
#include <string>

class Something
{
public:
    Something(const std::string& str) : mStr(str) {}
    const std::string& str() const
    {
        return mStr;
    }
private:
    std::string mStr;
};

int main()
{
    Something* something;
    {
        std::string temp = "Testing.";
        something = new Something(temp);
    }

    std::cout<<something->str()<<"\n";
    delete something;
    return 0;
}

Is that std::string still valid or is it deleted? (In the object itself)

Upvotes: 1

Views: 3126

Answers (3)

michael henson
michael henson

Reputation: 158

You are correct, except you are missing the fact that mStr(str) makes a copy of str. This copy is destroyed in ~Somthing();

Upvotes: 3

James McNellis
James McNellis

Reputation: 355367

The data member mStr is of type std::string (it's an object, not a reference).

Therefore, when you initialize it in the constructor's initialization list (via : mStr(str)), the argument, which was passed by reference, is copied. In your example, only the initialization causes a copy to be made: if you removed the initialization, no copies would be made.

Upvotes: 6

Pavel Strakhov
Pavel Strakhov

Reputation: 40522

Contents of temp variable is copied to mStr. The code is valid.

Upvotes: 3

Related Questions