gpt4 book ai didi

c++11 - 为什么 C++ 标准不禁止这种可怕的用法?

转载 作者:行者123 更新时间:2023-12-01 10:12:00 24 4
gpt4 key购买 nike

源代码非常简单,不言自明。问题包含在评论中。

#include <iostream>
#include <functional>

using namespace std;
using namespace std::tr1;

struct A
{
A()
{
cout << "A::ctor" << endl;
}

~A()
{
cout << "A::dtor" << endl;
}

void foo()
{}
};

int main()
{
A a;
/*
Performance penalty!!!

The following line will implicitly call A::dtor SIX times!!! (VC++ 2010)
*/
bind(&A::foo, a)();

/*
The following line doesn't call A::dtor.

It is obvious that: when binding a member function, passing a pointer as its first
argument is (almost) always the best way.

Now, the problem is:

Why does the C++ standard not prohibit bind(&SomeClass::SomeMemberFunc, arg1, ...)
from taking arg1 by value? If so, the above bind(&A::foo, a)(); wouldn't be
compiled, which is just we want.
*/
bind(&A::foo, &a)();

return 0;
}

最佳答案

首先,您的代码还有第三种选择:

bind(&A::foo, std::ref(a))(); 

现在,为什么默认情况下参数被复制?我想,但这只是一个大胆的猜测,认为 bind 默认行为独立于参数生命周期是更可取的:绑定(bind)的结果是一个仿函数,它的调用可能会延迟很长时间参数销毁。

您是否期望以下代码默认产生 UB ?

void foo(int i) { /* ... */ }

int main()
{
std::function<void ()> f;

{
int i = 0;
f = std::bind(foo, i);
}

f(); // Boom ?
}

关于c++11 - 为什么 C++ 标准不禁止这种可怕的用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4322724/

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