小编The*_*Zoo的帖子

为什么复制构造函数不是仅仅因为有用户定义的析构函数就变得微不足道?

以下摘录使用Clang-libstdc ++或Clang-libc ++,GCC,它们的许多版本以及该语言自11(14&17)以来的所有三个版本进行编译:

#include <type_traits>

struct HasUserDefinedDestructor {
    ~HasUserDefinedDestructor() {}
};

using HUDD = HasUserDefinedDestructor;

static_assert(not std::is_trivially_move_constructible<HUDD>::value, "");
static_assert(not std::is_trivially_copy_constructible<HUDD>::value, "");
Run Code Online (Sandbox Code Playgroud)

这使我感到惊讶,因为复制仅需要微不足道的操作。

这是编译器/库中的错误吗,还是标准在某处说明使用用户定义的析构函数会使复制和移动构造函数变得微不足道?

Edit: Why this is not a repeat of default construction question: Given the comments we know "noexceptness" and triviality of constructors are affected by the noexceptness and triviality of the destructor, but before knowing that all of these traits are related the questions are different. Having this question allows anybody to see this is related

c++ type-traits language-lawyer template-meta-programming

6
推荐指数
1
解决办法
212
查看次数

是否可以使用placement-new来更改多态对象的类型?

是否可以使用placement-new来更改多态对象的类型?如果没有,标准中究竟禁止它的是什么?

考虑以下代码:

#include <new>

struct Animal {
    Animal();
    virtual ~Animal();
    virtual void breathe();
    void kill();
    void *data;
};

struct Dead: Animal {
    void breathe() override;
};

void Animal::kill() {
    this->~Animal();
    new(this) Dead;
}
Run Code Online (Sandbox Code Playgroud)

称"杀人"是否合法?

更新:早期的注释没有根据此处所示的编程技术标准来解决(il)合法性,即通过显式调用析构函数来更改对象的类型,并为兼容的新对象应用placement-new.

因为有兴趣为什么有人愿意这样做,我可以提一下导致我提出问题的用例,尽管它与我提出的问题无关.

想象一下,您有一个具有多个虚拟方法的多态类型层次结构.在对象的生命周期中,发生的事情可以在代码中建模,因为对象会更改其类型.有许多完美合法的方法来编程,例如,将对象保持为指针,智能与否,以及交换其他类型的副本.但这可能很昂贵:必须将原始对象克隆或移动到另一个不同类型的对象中才能交换新的对象.

在GCC,Clang和其他人中,更改对象的类型可以像简单地更改虚拟表指针一样便宜,但在便携式C++中,除了通过构造新类型的对象之外,这是不可能的.

在我的原始用例中,对象也不能作为指针.

我想知道标准在重用内存方面的内容.

c++ polymorphism placement-new language-lawyer

5
推荐指数
1
解决办法
339
查看次数

为什么 STL 容器适配器堆栈中的 top 返回一个 const 引用?

容器适配器的规范stack说top应该返回一个const引用。为什么?

queue'sfront和也会发生同样的问题back。我可以看到在这种情况下priority_queue,可修改的访问可能会干扰优先级,从而导致“类不变量”,但我不知道为什么您不能修改topastack或front,backa 的原因queue。

为规范最实用的代理是cppreference.com: 顶部

您可以看到它返回 a const_reference,它是const对适应的底层容器所持有的值的引用。

c++ containers stl

0
推荐指数
1
解决办法
82
查看次数