r/cpp • • Jun 13 '24

Limit the number of library dependencies

https://www.sandordargo.com/blog/2024/06/12/builds-and-dependencies
0 Upvotes

12 comments sorted by

10

u/goranlepuz Jun 13 '24
void baz(std::unique_ptr<Storage> s) { 	
  // You don't need the implementation of Storage::addItem here
 	auto res = s->addItem(Item{"whatnot", 42});

I also don't need unique ptr nor the optional nature of a pointer, nor does the caller need the usage of the heap.

11

u/dustyhome Jun 13 '24

Also, you require that the caller move storage into the function, add an item to the storage, and then destroy the storage when the function ends.

4

u/goranlepuz Jun 13 '24

Ah, true.

Hilarious, in the end, isn't it?!

1

u/beephod_zabblebrox Jun 14 '24

would you even be able to call this function? doesnt this invoke the deleted copy constructor

1

u/dustyhome Jun 14 '24

You can't just give it a unique_ptr you own. You have two ways of calling it, you either move:

void f() {
  auto s = someFactoryFunctionReturningAStorageUniquePtr());
  // ...
  baz(std::move(s));
}

Or you create a new storage for it:

void f() {
  baz(someFactoryFunctionReturningAStorageUniquePtr());
}

1

u/beephod_zabblebrox Jun 14 '24

wouldn't that require the argument to be an r-value ref?

2

u/dustyhome Jun 14 '24

No, an r-value ref parameter requires an r-value (so a temporary or something you called std::move on), but a "by value" parameter can accept values you can construct the parameter with. Here are some examples: https://godbolt.org/z/shbszvna6

#include <memory>

void byValue(std::unique_ptr<int>);

void f() {
    auto intPtr = std::make_unique<int>(42);
    //byValue(intPtr); // ERROR, calls deleted copy constructor
    byValue(std::move(intPtr)); // fine, we move the original ptr
    byValue(std::make_unique<int>(42)); // fine, we create from a temporary
    //byValue(new int(42)); // ERROR, ptr constructor is explicit, so int* not implicitly convertible
    byValue(nullptr); // fine, unique_ptr is implicitly convertible from nullptr_t
    byValue(std::unique_ptr<int>{new int(42)}); // fine, we call the constructor explicitly
}

1

u/beephod_zabblebrox Jun 14 '24

ohh yeah that makes sense, thanks

my brain is mush in the morning haha

12

u/Stanczyk4 Jun 13 '24

No

7

u/johannes1971 Jun 13 '24

Succinct, but the article is so vapid that it really says it all...

6

u/prince-chrismc Jun 13 '24

why it’s important to limit the number of dependencies your APIs have

That should have been the title, this was super misleading.

Actually header_only libraries are a bigger factor to slow downs then linking is that does not really hold much air.

0

u/[deleted] Jun 13 '24

[deleted]

2

u/petamas Jun 14 '24

Why did you decide to migrate to conan? How does a different package manager solve your problem? The same problem occurs there, too, or I misunderstood what you're talking about.