Created
September 19, 2025 22:16
-
-
Save dhilst/44fcf0f0bb2aae8f3f5055cfa70669a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <memory> | |
| namespace foo { | |
| // Here is how to create read only objects in C++23 | |
| // Step 1, define a class | |
| class foo { | |
| std::string m_bar; | |
| int m_tar; | |
| bool m_zar; | |
| // Step 2, make the constructor private | |
| foo(std::string bar, int tar, bool zar) | |
| : m_bar(bar), m_tar(tar), m_zar(zar) {} | |
| public: | |
| // Step 3, add two factory method/smart constructors | |
| // friend class is a preference here, static method just work | |
| // without requiring friend | |
| // Read only | |
| friend auto ro(std::string bar, int tar, bool zar) | |
| -> std::unique_ptr<const foo>; | |
| // Mutable | |
| friend auto rw(std::string bar, int tar, bool zar) | |
| -> std::unique_ptr<foo>; | |
| // Step 4, add move semantics, std::make_unique will | |
| // make use of it | |
| foo(foo&&) = default; | |
| foo& operator=(foo&&) = default; | |
| foo(const foo &) = delete; | |
| foo& operator=(const foo&) = delete; | |
| ~foo() = default; | |
| // Step 5, add methods | |
| auto tar() const -> decltype(auto) { return m_tar; } | |
| auto tarinc() -> decltype(auto) { return ++m_tar; } | |
| }; | |
| // Our beaultifuly smart constructors | |
| auto ro(std::string bar, int tar, bool zar) | |
| -> std::unique_ptr<const foo> { | |
| return std::make_unique<const foo>(foo(bar, tar, zar)); | |
| } | |
| auto rw(std::string bar, int tar, bool zar) | |
| -> std::unique_ptr<foo> { | |
| return std::make_unique<foo>(foo(bar, tar, zar)); | |
| } | |
| } // namespace foo | |
| int main(void) | |
| { | |
| auto foo1 = foo::ro("bar", 1, true); | |
| auto foo2 = foo::rw("bar", 1, true); | |
| std::cerr << "Foo1: " << foo1->tar() << std::endl; | |
| std::cerr << "Foo2: " << foo2->tar() << std::endl; | |
| // 1. 'this' argument to member function 'tarinc' has type 'const foo::foo', | |
| // but function is not marked const [member_function_call_bad_cvr] | |
| // foo1->tarinc(); | |
| foo2->tarinc(); | |
| std::cerr << "Foo1: " << foo1->tar() << std::endl; | |
| std::cerr << "Foo2: " << foo2->tar() << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment