我目前正在按照 ChiliTomatoNoodle 的教程编写我的第一个应用程序,并根据我的需要修改他的代码。在这样做并实现一个简单的 WindowManager 类时,它的目的是将所有窗口实例存储在 std::vector 和类似的东西中,我收到以下错误消息:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\xmemory(758,1):
error C2280: 'Window::Window(const Window &)': attempting to reference a deleted function (compiling source file src\cpp\WindowManager.cpp)
问题似乎在于 addWindow
函数,其中窗口被实例化并存储在 std::vector<Window> Wnd
中:
void WindowManager::addWindow(unsigned short x, unsigned short y, unsigned short width, unsigned short height, const char* name, Window::WindowClass& windowClass, DWORD style) {
this->Wnd.emplace_back(Window(name, x, y, width, height, windowClass, style, this->IdGenNum++));
}
我已经改了push_back
至 emplace_back
可能会避免复制(?),但这并没有解决问题。
然后还有一个getter(好像没问题,没有复制任何东西):
Window& WindowManager::getWindow(const unsigned short id) {
for (Window &element : this->Wnd) {
if (element.Id == id) {
return element;
}
}
}
这里是 Window
类头:
class Window {
private: // Friends
friend class WindowManager;
public: // Nested Classes
class WindowClass {
...
};
private: // Variables and Instances
unsigned short Id; // Received by WindowManager on Creation
const char* Name;
HWND Handle;
...
public: // Constructors and Deconstructors
Window(const Window&) = delete;
Window(
const char* name,
unsigned short x,
unsigned short y,
unsigned short width,
unsigned short height,
WindowClass& windowClass,
DWORD style,
unsigned short id
);
~Window();
private: // Functions
...
public: // Operators
Window& operator=(const Window&) = delete;
};
编辑:
感谢所有指出参数必须直接传递给 emplace_back
的回答和评论方法。事实证明, vector 仍然复制了对象(不知道为什么......),但我可以通过使用 std::list
来解决这个问题。相反,它没有这种行为。
最佳答案
Window
复制构造函数是用 delete
声明的,但是当您将现有的 Window
对象传递给 emplace_back()
,emplace_back()
的实现将尝试使用其参数就地构造另一个 Window
对象。它可以做到这一点的唯一方法是尝试使用已删除的复制构造函数。
您可以声明一个复制构造函数,使用 push_back()
,或者甚至更好地调用 emplace_back()
使用您的其他 Window
构造函数,它将避免复制。
关于c++ - 在 std::vector 中实例化对象时出现错误 C2280/复制构造函数问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58310942/