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

标签 c++ struct constants copy-constructor default-constructor

我有一个 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/

相关文章:

c++ - 如何延迟初始化全局变量?

c++ - 为什么不允许 "inlined"静态常量,整数除外?

c++ - 为什么可以将枚举作为函数变量传递但不能返回枚举?

objective-c - 结构内存分配(泄漏和崩溃,iPhone 上的分析)

c++ - 在没有给定值的复制构造函数的情况下初始化 const 成员?

c++ - 增加顶级 const 指针时发生了什么?

c++ - Erlang/OTP ./configure 失败打开 Solaris

c++ - 抛出异常 : write access violation. newNode 为 nullptr

c# - 创建结构值的性能

c - 程序中打印无效字符