gpt4 book ai didi

c++ - 具有常量成员的结构的默认复制操作

转载 作者:行者123 更新时间:2023-11-30 03:43:07 25 4
gpt4 key购买 nike

我有一个 Texture 结构,我用它来保存纹理的宽度、高度和 ID 号。我还有一个 Loader 类,其中包含许多专用于加载内容(例如纹理)的静态函数。当我尝试声明一个未初始化的 Texture,然后稍后对其进行初始化时,问题就出现了。这是 Texture.h 中的代码:

namespace bronze {

struct Texture {
const unsigned int id;
const float width;
const float height;

Texture() = default;
Texture(Texture&&) = default;
Texture& operator=(Texture&&) = default;
};

}

Loader.cpp

Texture(const std::string& file, float scale) {
unsigned int id;
float width, height;

loadTextureUsingExternalLibrary(&id, &width, &height);
doThingsWithTexture(id);

return Texture{id, width, height}
}

然后在 main.cpp 中:

#include "Loader.h"
#include "Texture.h"

using namespace bronze;

Texture tex;

int main() {
tex = Loader::loadTexture("asdf.png", 2.f);
drawTextureOnTheWindowSomehow(tex);
return 0;
}

这是我遇到的(当然是缩短的)错误(MinGW 是我的编译器):

error: use of deleted function 'bronze::Texture::Texture()'
Texture tex;

note: 'bronze::Texture::Texture()' is implicitly deleted because the default
definition would be ill-formed:
Texture() = default;

...complains about each member being uninitialized

error: use of deleted function 'bronze::Texture& bronze::Texture::operator=
Bronze::Texture&&)'
tex = Loader::loadTexture("asdf.png", 2.f);

note: 'bronze::Texture& bronze::Texture::operator=(bronze::Texture&&)' is
implicitly deleted because the default definition would be ill-formed:
Texture& operator=(Texture&&) = default;

...complains for each struct member that "non-static const member can't use
default assignment operator"

我已经在谷歌上搜索了一段时间,但找不到任何东西。也许是我不知道谷歌什么,我不知道。感谢您的帮助!

最佳答案

这几个部分

1. 默认构造函数不起作用,因为您不能拥有未初始化的 const 对象(即使是基元)。对于您的简单情况,您可能只希望对它们进行值初始化,这很容易实现:

struct Texture {
const unsigned int id{};
const float width{};
const float height{};
//...
};

2.您不能对具有const 数据成员的对象使用隐式生成的operator=,因为这需要分配给const 对象。

struct A { const int i{}; };
A a1;
A a2(a1); // fine
a1 = a2; // not fine. can't do a1.i = a2.i since a1.i is const!

如果你想赋值,你需要使用非常量数据成员。 如果你有 const 成员,你不能使用隐式运算符=* 你可以 const_cast 但这会导致未定义的行为并且是一个可怕的想法(只是在有人提到之前说出来它在评论中)。

您不仅仅是在声明 tex,您还在定义它。定义点需要初始化。稍后尝试分配并不是初始化它。

不要使用全局变量。

*除非那些 const 成员有一个 operator=(..) const 但那会很奇怪

关于c++ - 具有常量成员的结构的默认复制操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36322138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com