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)
The data member
mStris of typestd::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.