- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
以这两个类为例:
struct Owned {
Owned() : i() { }
void print() { cout << ++i << endl; }
int i;
};
struct Owner {
Owner(Owned& o) : o(o) { }
Owned& o;
~Owner() { o.print(); }
};
这样使用它们有危险吗?
int main() {
Owned owned;
Owner owner(owned);
}
看起来,根据它们被销毁的顺序,这可能会导致 owner
的析构函数调用被销毁的 owner
上的函数。是否定义了局部变量的销毁顺序,如何使两个实例相互引用的情况起作用?
如果这是常识,请原谅我,不过我还没有在任何地方读到任何相关内容。
最佳答案
局部变量的销毁顺序与创建顺序相反。在你的情况下,你很好,因为 owner
总是会在 owned
之前被销毁。
§6.6 [stmt.jump] p2
On exit from a scope (however accomplished), objects with automatic storage duration (3.7.3) that have been constructed in that scope are destroyed in the reverse order of their construction.
但是,如果您可以在构造后重新分配拥有的成员,则必须小心。
how can you make a situation where two instances refer to each other work?
不要让它们在析构函数中相互访问。或者弄清楚谁先被销毁,也许有一个回调或传递的标志。示例:
struct two;
struct one{
two* other;
one(two* o = nullptr) : other(o) {}
~one(){ if(other) other.other = nullptr; }
};
struct two{
one* other;
two(one* o = nullptr) : other(o) {}
~one(){ if(other) other.other = nullptr; }
};
这将确保两个对象永远不会引用不存在的对象。
无论如何,相互引用的对象是非常罕见的。
关于c++ - 局部变量引用其他局部变量是否危险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827376/
编辑:澄清一下,我明白为什么这段代码不起作用,我并不是要修复它,而是想了解如果这段代码可以在没有语义错误的情况下编译会有什么危险。 我发现下面的代码会导致静态语义错误。我知道这是因为 std::lis
我想知道 C# 枚举以及重复值会发生什么。我创建了以下小程序来测试: namespace ConsoleTest { enum TestEnum { FirstElem
正如我在另一个 SO 问题中指出的那样,我遇到了 this article .当我通过 MSVC7.1 编译 boost 1.40 时出现了这个问题,并且弹出了几个 C4251 警告。 现在,在阅读上
我有以下弹出窗口代码(客户端请求)。它使用 eval ,我知道这是危险的。有没有办法重写下面的脚本,使其不使用 (eval)? /* exported popup_default , popup_he
NTFS 文件可以有对象 ID。可以使用 FSCTL_SET_OBJECT_ID 设置这些 ID .然而,msdn article说: Modifying an object identifier c
我一直在学习命令行参数解析。关于这个已经有很长的线索了,我不想在这里挑起一个: Using getopts in bash shell script to get long and short com
这个问题在这里已经有了答案: How to configure ContextMenu buttons for delete and disabled in SwiftUI? (4 个回答) 4 个月
为什么在 linux 的中断处理程序中禁止 printk 或 (I/O)。?在什么情况下中断处理程序中的 I/O 会导致 linux 系统中的死锁? 最佳答案 关于 printk(),它是侵入性的。例
不是 Invoking virtual function and pure-virtual function from a constructor 的重复项: 以前的问题与 C++ 03 相关,而不是
我正在使用 lateinit 属性以避免使用 ?运算符(operator)。我有很多 View 属性是第一次在 getViews() 函数中分配的。如果该功能不存在,我的应用程序将与来自 Kotlin
我最近在使用 fputs 时遇到了问题:当使用 fputs 在文本文件中打印一些字符串时,我碰巧得到了除 A-Z、a-z、0-9 之外的其他字符(不属于字符串的字符) .我绝对确保所有字符串都以空字符
在仅包含字节数组的结构上使用 #pragma pack(1) 是否危险/有风险?例如。这个: #pragma pack(1) struct RpcMessage { uint8_t proto
我是一名优秀的程序员,十分优秀!