Skip to content

<optional>: std::optional move constructor moves a const object #2458

Description

@fsb4000

Describe the bug
A simple example below shows that the move constructor of the contained object is invoked when an std::optional is move-constructed from another instance of std::optional. This behavior is (1) surprising and (2) different from that of libc++/libstdc++.

https://godbolt.org/z/5qxT4v8xd

Command-line test case

C:\Temp>type main.cpp
#include <iostream>
#include <utility>
#include <optional>

struct Copyable {
    Copyable() = default;
    Copyable(const Copyable&) {
        std::cout << "Copyable copied\n";
    }
    Copyable(Copyable&&) {
        std::cout << "Copyable moved\n";
    }
};

template <typename TYPE>
void testMove() {
    std::optional<TYPE> orig;
    orig.emplace();
    std::optional<TYPE> moved = std::move(orig);
}

int main() {
    testMove<Copyable>();
    testMove<const Copyable>();
}

C:\Temp>cl /EHsc /W4 /WX /std:c++17 .\main.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.31.30818 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

main.cpp
Microsoft (R) Incremental Linker Version 14.31.30818.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj

C:\Temp>.\main.exe
Copyable moved
Copyable moved

Expected behavior
Copyable moved
Copyable copied

STL version
Microsoft Visual Studio Community 2022 Preview
Version 17.1.0 Preview 1.1

Additional context
DevCom-1628644

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions