Вам нужно только передать умный указатель на функцию, если вы имеете в виду также указать право собственности на указатель.
Я недавно написал статью о семантике собственности при передаче std :: unique_ptr в/из функций. Посмотрите http://timoch.com/blog/2013/04/std-unique_ptr-semantic/
Учитывая структуру A:
struct A { int field; };
Passing сырой указатель
// you make no statement of ownership
// the caller stays the owner of the pointed object
void useA(A* ptr) {
// useA simply uses the pointed object
// it should not delete it (because it does not own it)
ptr->field = 2;
}
Передача по значению
std::vector<std::unique_ptr<A>> container;
// the caller explicitly gives you ownership of the object
void ownA(std::unique_ptr<A> ptr) {
// you can use the pointed object
std::cout << ptr->field << std::endl;
// the object pointed to by ptr is yours
// you can place it in a container that you own
container.push_back(std::move(ptr));
// now container owns the pointed A instance
// if you do not move it using std::move()
// the pointed object is deleted automatically
}
Проходя мимо неконстантного ссылки
// the caller is giving you the opportunity to take ownership of the object
// it is free to not take it though
void maybeOwnA(std::unique_ptr<A> & ptr) {
// ptr is passed by reference
// so maybeOwnA can decide based on its own internal
// to take ownership of the pointed object
// taking ownership requires that std::move is called on ptr
// it may also simply use the pointed object and not
// take ownership
}
void callMaybeOwnA() {
std::unique_ptr<A> ptr = new A();
maybeOwnA(ptr);
// we know if we still own the instance of A
// by looking at ptr
if (ptr.get() != nullptr) {
// we still own the pointed object
}
}
Проходя по константной-ссылки
// this is functionally the same as passing a raw pointer
// but you force the caller to use a std::unique_ptr to call you
// the caller will not be able to use a std::shared_ptr for example
// I strongly recommend against this form. Passing a raw pointer is
// perfectly fine
void useA(const std::unique_ptr<A> & ptr) {
// ptr is const so you cannot call std::move on it
// you effectively cannot own it
}
// a factory function should return a std::unique_ptr by value
// the caller owns the pointed object
std::unique_ptr<A> factory() {
return std::unique_ptr<A>(new A());
}
void callFactory() {
std::unique_ptr<A> ptr = factory();
// the pointed object is deleted when ptr goes out of scope
}
То же самое относится и к станд :: shared_ptr. Если функция просто использует указатель и возвращает, нет никаких оснований передавать std :: shared_ptr. Вам просто нужно передать std :: shared_ptr, когда вы хотите предоставить совместное владение заостренным объектом к компоненту, которому вы звоните. Например, если функция сохранит указатель и ожидает, что сможет использовать его после его возврата (например, при вызове снова).
Надеюсь, это поможет.
TiMoch
Единственный способ определения производительности - измерение. Угадать или пытаться вычислить его обычно неправильно, поскольку компилятор выполняет так много оптимизаций, что большая часть кода фактически удаляется. Напишите код меры и оптимизируйте соответствующим образом. – 2010-11-24 08:36:04