标签: memory-aliasing

为什么将容器的元素分配给容器(而不是)定义良好的 C++?

在 C++ 中,存在臭名昭著的自赋值问题:在实现 时operator=(const T &other),必须小心,this == &other不要this在从 复制数据之前破坏 的数据other

然而,*thisother可能以比作为同一个对象更有趣的方式交互。即,一个可以包含另一个。考虑以下代码:

#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Foo {
    std::string s = "hello world very long string";
    std::vector<Foo> children;
};
int main() {
    std::vector<Foo> f(4);
    f[0].children.resize(2);
    f = f[0].children;  // (1)
    // auto tmp = f[0].children; f = std::move(tmp);  // (2)
    std::cout << f.size() << "\n";
}
Run Code Online (Sandbox Code Playgroud)

我希望行(1)(2)是相同的:程序被明确定义为 print 2。然而,我还没有找到一个编译器+标准库组合,可以与启用的行 …

c++ assignment-operator language-lawyer copy-assignment memory-aliasing

4
推荐指数
1
解决办法
129
查看次数