3 ms·
> You'll get 4 instructions (don't forget to put __attribute__((noinline)) on add_numbers()): That's 4 instructions only for add_numbers(), but add_two_numbers
by codedokode 4y ago
> You'll get 4 instructions (don't forget to put __attribute__((noinline)) on add_numbers()):
That's 4 instructions only for add_numbers(), but add_two_numbers_smart_way() still is unoptimized.
- UkrainianJew 4y agoWell, you can somewhat simplify it: int add_two_numbers_smart_way(int a, int b) { auto x = std::make_shared<Data>(a, b); return add_numbers(x); } But you still get what you ask the compiler to deliver. If you don't specifically ask it to count references, it won't: static int add_numbers(Data *p) { return p->a + p->b; } int add_two_numbers_smart_way(int a, int b) { Data x(a, b); return add_numbers(&x); } Here's the result: add_two_numbers_smart_way(int, int): lea eax, [rdi + rsi] ret To answer the original question, it won't optimize the smart pointers away because the smart pointers are not implemented by the compiler. They are a generic construct telling the compiler to allocate memory, increase reference counter, decrease reference counter and free memory. How does it now this is not a unit test for memory allocation API or atomic operations? A better question would be why C++ went for implementing certain things on the library level instead of the compiler level, and the answer here is probably "historical reasons" and someone's judgement call on flexibility vs performance under specific circumstances.
- gumby 4y agoIt’s not “C++’s” decision, it’s the compiler writer’s. Compilers are full of special handling of standard functions (memcpy is a common case) — those cases are called “compiler intrinsics”. They can also choose to call a function when you don’t expect it (e.g. when your hardware doesn’t have floating point support). Does rust try to follow the platform C ABI? C++ implementations typically do when it is semantically meaningful.
- steveklabnik 4y agoRust doesn’t follow the platform C ABI unless you ask for it specifically. If you do, it will, and if you don’t, the ABI is unspecified for a reason.
- gumby 4y agoI wish c++ could get away with this. But the two languages (c++ and rust) explore slightly different parts of the design space.
- bjourne 4y agoSTL lets you supply a custom allocator for all STL types. Afaik, Rust doesn't and this is probably the price you have to pay for that feature.
- steveklabnik 4y agoBox is parameterized by an allocator: https://doc.rust-lang.org/stable/std/boxed/struct.Box.html https://doc.rust-lang.org/stable/std/boxed/struct.Box.html Rust doesn’t let you utilize this fact on stable yet, which is what you’re thinking of, but the implementation in this case already exists.
- vasama 4y agoIf by "STL" you mean the standard library, it's not true that _all_ containers accept allocators. At least valarray and filesystem::path do not accept allocators.