4 ms·
> The assignment into the object will do the copy constructor and that needs a non-const ref. Hum? What assignment into the object? Where I'd typically see tak
by tomjakubowski 11y ago
> The assignment into the object will do the copy constructor and that needs a non-const ref.
Hum? What assignment into the object? Where I'd typically see taking a `const std::shared_ptr<> &` to signal "retaining ownership" would be something like this:
class Foo {
public:
void AppendChild(const std::shared_ptr<Foo> &x) {
children_.emplace_back(x);
}
private:
std::vector<std::shared_ptr<Foo>> children_;
};
Why should Foo:;AppendChild's signature be changed to a non-const ref?
- corysama 11y agoYou are correct. I had a brain fart. Edited my comment.
- millstone 11y agoIt should be changed to pass by value, and then use std::move to move it into the children array. The reason is that if the argument is a temporary, you are making an unnecessary copy of that temporary, when you could just transfer ownership. This also gives callers the flexibility to std::move into your argument, transferring ownership. A good rule of thumb is, if you are going to unconditionally take ownership of an object, accept it by value.