0

I have the following code.

#include <iostream>
#include <unordered_map>

struct Object {
    ~Object() noexcept = default;
    Object() noexcept = default;
    Object(const Object&) = delete;
    Object(Object&&) noexcept = default;
    Object& operator=(const Object&) = delete;
    Object& operator=(Object&&) noexcept = default;

    std::unordered_map<int, int> map{};
};

Object get_object() {
    Object o{};
    o.map[0] = 1;
    return o; // error
}

int main() {
    Object o = get_object();
    std::cout << o.map[0] << '\n';
    return 0;
}

The static analysis in Visual Studio 2022 shows the following error.

Line 18: function "Object::Object(const Object &)" (declared at line 7) cannot be referenced -- it is a deleted function

However, the code compiles just fine and the result is 1 as expected.

What actually happens? Can std::unordered_map be really moved? If this isn't a problem, how can I tell the static analysis that this is a false positive?

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33
  • 2
    The VS IntelliSense is using a different compiler than the actual compiler itself. They can give different diagnostics for the same code. – Some programmer dude Dec 29 '22 at 11:04
  • 1
    https://stackoverflow.com/questions/21206359/in-which-situations-is-the-c-copy-constructor-called – dorKKnight Dec 29 '22 at 11:06
  • 1
    @dorKKnight What is this supposed to say? The copy constructor isn't called, otherwise it won't compile. – sanitizedUser Dec 29 '22 at 11:07
  • 1
    get_Object() is trying to return by value so copy constructor comes into play and it is (as the error message points out) a 'deleted function'. – dorKKnight Dec 29 '22 at 11:07
  • @dorKKnight But there are all conditions for copy ellision, so it calls move constructor. What are you trying to say? – sanitizedUser Dec 29 '22 at 11:08
  • 1
    Even if an object-copy is elided, the copy-constructor still needs to be possible to call. – Some programmer dude Dec 29 '22 at 11:20
  • What is the error number of this message? If there are none, then it could be a warning, and if it doesn't have a warning number, then it's a comment, not an error message. The copy constructor is not needed for in-place return, nor is the move constructor. – Michaël Roy Dec 29 '22 at 13:22
  • 1
    In this example, copy-constructor is required before C++17, not required in C++17 and up (C++17 introduced mandatory copy elision). It seems that, somehow or other, the static analysis uses pre-C++17 rules. – Igor Tandetnik Dec 29 '22 at 14:42
  • 1
    @MichaëlRoy The error code is E1776. – sanitizedUser Dec 29 '22 at 15:39
  • [C++ Intellisense error E1776: deleted rvalue ref'd operator, compiles fine](https://developercommunity.visualstudio.com/t/false-positive-for-c2280-in-gui-deleted-rvalue-ref/853855) – Some programmer dude Dec 29 '22 at 20:00

0 Answers0