Date: Tue, 29 Apr 2025 18:30:37 +0200
Hi YexuanXiao,
much more important than performance is correctness.
So the ownerhsip of the types is very important and combined with it, whether they rely on any object outliving your storage.
To be flexible, why not always store a (pointer or) reference?
That would not be a std::unique_ptr or a std::shared_ptr, as a std::unique_ptr signifies ownership and would deallocate and a std::shared_ptr only works, if you use std::shared_ptr also for the provided storage.
It would just be a standard pointer or reference type.
You could try to optimize double redirections away by detecting whether the type already is a pointer or simple small-sized type like int. But then you could use the size as criteria. If the size is larger than a pointer to the object (often 8 bytes) then use a pointer.
To get the same result, you need to make sure that the underlying object is not modified, as long as you store a pointer to it.
Best,
Sebastian
-----Ursprüngliche Nachricht-----
Von:Yexuan Xiao via Std-Proposals <std-proposals_at_[hidden]>
Gesendet:Di 29.04.2025 18:27
Betreff:[std-proposals] Cheap but Non-Trivial Copy Trait
An:std-proposals_at_[hidden];
CC:Yexuan Xiao <bizwen_at_[hidden]>;
Hey everyone,
I previously wrote a JSON library aiming to precisely represent JSON objects in C++. Recently, I have been contemplating how to optimize its design. In my library, there is a node type that stores an allocator, a type tag, and a union containing arithmetic types and pointers to large objects. Copying it is cheap, and its triviality depends on the allocator. It does not own the objects, behaving like a pointer, allowing arbitrary copies. Today, I realized that the String type could be stored directly as a value within the node instead of storing its pointer, when copying the String is cheap.
What types of copies are considered cheap? Undoubtedly, all trivially copyable types. However, reference-counted types like Qt’s QString and Windows’ winrt::hstring also exhibit cheap copying, even though their copy-constructors are not trivial. These types typically pointer-sized. If I can efficiently detect such types and store them directly in the node rather than allocating them on the heap and storing pointers, memory allocations could be significantly reduced.
In other words, a trait that std::string_view, winrt::hstring, and QString satisfy—but std::string does not, would allow generic code to store such types by value without wrapping them in std::unique_ptr or other wrappers. It can be implemented as follows and allows users to specialize:
template<class T> struct is_cheap_copy_constructible : is_trivially_copy_constructible{};
template< class T >
inline constexpr bool is_cheap_copy_constructible_v =
is_cheap_copy_constructible<T>::value;
Any feedback is welcome.
Best regards,
YexuanXiao
--
Std-Proposals mailing list
Std-Proposals_at_[hidden]
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
Received on 2025-04-29 16:37:26