문제

Taking this as an example:

#include <memory>
#include <iostream>

int add(int a, int b) {
    return a+b;
}

std::unique_ptr<int> addp(int a, int b) {
    std::unique_ptr<int> ip(new int(a + b));
    return ip;
}

int main(int argc, char const* argv[])
{
    std::cout << add(3, 5) << std::endl;
    std::cout << *(addp(3, 5)) << std::endl;
    return 0;
}

does the function addp give any improvement in performence, or in other words, does it avoid the copying of data at all? I am suspecting that the result a+b is got in the stack and then copied to the heap any way.

도움이 되었습니까?

해결책 3

No, addp is likely a lot slower as it requires a heap allocation.

Thanks to return value optimization (RVO) the compiler will probably optimized the copy out of the original add function anyway.

다른 팁

You don't need any pointers at all here, so smart pointers aren't an improvement.

Smart pointers bring an improvement to a pointer-driven code by attaching resource ownership information (e.g. which part is responsible for freeing a resource) to variables.

The benefit of using a smart pointer is not having to use a "naked" pointer in the case of needing one.

Thus, this is not related to performance: it is related to the need of the programmer awareness of memory management, which increases the software complexity, possibly increasing the number of bugs and memory leaks.

If you wanted, as you said, to avoid the copying of data to the function, you could use pass-by-refence, so that the function receives a reference to the object, instead of a copy of it. Also, be aware that by doing so, any changes made to the parameters inside the function will be applied to the original caller. To avoid this, you can use const.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top