[英]Is it possible to avoid the copy constructor when passing newly created object to a function?
I'm trying to figure out is it possible to avoid calling the copy-constructor when passing a just-created object to a function? 我想弄清楚是否可以避免在将刚刚创建的对象传递给函数时调用copy-constructor? I don't want to use this object any more, I'd just like to name the temporary and pass it by value to some other function.
我不想再使用这个对象,我只想命名临时值并将其传递给其他函数。
I know that in C++11 I can just move this object, but I'm concerned how to improve this in C++03. 我知道在C ++ 11中我可以移动这个对象,但我担心如何在C ++ 03中改进它。 So essentially, I'm interested in eliminating the copy-constructor call in the code below:
基本上,我有兴趣在下面的代码中消除copy-constructor调用:
Snippet: 片段:
#include <iostream>
struct Foo
{
Foo(void) { std::cout << "Default ctr\n"; };
Foo(const Foo& f) { std::cout << "Copy ctr\n"; }
};
void bar(Foo f)
{
std::cout << "Inside bar\n";
}
int main()
{
Foo f;
bar(f);
bar(Foo());
}
Possible result: 可能的结果:
Default ctr
Copy ctr
Inside bar
Default ctr
Inside bar
Compilation string: 编译字符串:
g++ -O3 -Wall -pedantic main.cpp && ./a.out
Ie to use some kind of copy-elision but on an argument passed to a function, not on a return value (NRVO). 即使用某种类型的copy-elision但是在传递给函数的参数上,而不是在返回值(NRVO)上。
Pass by value implies copying. 按值传递意味着复制。 This copying can be elided but semantically pass by value is still copying.
这种复制可以省略,但语义上传递值仍然是复制。 You can pass by reference as well to avoid this copy.
您也可以通过引用传递以避免此副本。 Note that these are the only situations in which copy elision are permitted:
请注意,这些是允许复制省略的唯一情况:
That's why in: 这就是为什么:
bar(f);
bar(Foo());
only the second involves copy elision. 只有第二个涉及复制省略。 Pre-C++11, just use a reference or use Boost.
Pre-C ++ 11,只需使用引用或使用Boost。
Use this syntax: 使用以下语法:
void bar(const Foo& f)
{
std::cout << "Inside bar\n";
}
The above code passes the object as reference. 上面的代码将对象作为参考传递。 This effectively copies the address of the object only (like a pointer) but the reference can be handled like the original object.
这有效地仅复制对象的地址(如指针),但可以像原始对象一样处理引用。
You can use reference(or pointer) of class Foo as parameter to function bar(). 您可以使用类Foo的引用(或指针)作为函数bar()的参数。 This will avoid creation of temporary object, from the object passed as argument to function bar(),and hence no copy constructor will be called.
这将避免从作为参数传递给函数bar()的对象创建临时对象,因此不会调用复制构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.