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 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.
Contents of temp
variable is copied to mStr
. The code is valid.
You are correct, except you are missing the fact that mStr(str) makes a copy of str. This copy is destroyed in ~Somthing();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.