Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update optional.hpp #2828

Merged
merged 1 commit into from
Nov 12, 2024
Merged

Conversation

0blu
Copy link
Collaborator

@0blu 0blu commented Nov 9, 2024

🍰 Pullrequest

Upgrades nonstd::optional so move semantics are used and a default constructor is not required.
With this upgrade we will also have have access to monadics.

It will perform as good as the original std::optional implementation.

Old New
MyTestClass[0] new
MyTestClass[1 <- 0] copy
MyTestClass[0] dtor
MyTestClass[1] The actual function was called
MyTestClass[1] dtor
MyTestClass[0] new
MyTestClass[1 <- 0] move
MyTestClass[0] dtor
MyTestClass[1] The actual function was called
MyTestClass[1] dtor
Code to test
#include <iostream>
#include "nonstd/optional.hpp"

class MyTestClass final
{
public:
    MyTestClass() : m_mycount{g_counter++}
    {
        std::cout << "MyTestClass[" << m_mycount << "] new" << std::endl;
    }
    MyTestClass(MyTestClass&& other) noexcept : m_mycount{g_counter++}
    {
        std::cout << "MyTestClass[" << m_mycount << " <- " << other.m_mycount << "] move" << std::endl;
    }
    MyTestClass(MyTestClass const& other) noexcept : m_mycount{g_counter++}
    {
        std::cout << "MyTestClass[" << m_mycount << " <- " << other.m_mycount << "] copy" << std::endl;
    }
    ~MyTestClass()
    {
    std::cout << "MyTestClass[" << m_mycount << "] dtor" << std::endl;
    }

    void CallMe() const
    {
        std::cout << "MyTestClass[" << m_mycount << "] The actual function was called" << std::endl;
    }
private:
    int const m_mycount;
    static int g_counter;
};
int MyTestClass::g_counter;

nonstd::optional<MyTestClass> getAnOptionalInstance() {
    return nonstd::make_optional(MyTestClass());
}

int main()
{
    nonstd::optional<MyTestClass> maybeMyInstance = getAnOptionalInstance();
    if (maybeMyInstance)
        maybeMyInstance->CallMe();

    return 0;
}

@0blu 0blu added the CPP A issue / PR which references CPP code label Nov 9, 2024
@0blu 0blu force-pushed the improve-optional-backport branch from b8807d2 to 167cc23 Compare November 9, 2024 12:45
@ratkosrb ratkosrb merged commit fe659a6 into vmangos:development Nov 12, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CPP A issue / PR which references CPP code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants